C
C#2y ago
Bread

How do I 'build' a QUERY with EF Core?

Essentially I had an endpoint that can take multiple query string params, most are optional, so I want to check first if the query parameter exists - then if it does "add" it to the query. This keeps to be sending me errors and doesn't feel efficient; have I missed something?
12 Replies
Angius
Angius2y ago
var query = _context.Things.AsQueryable();

if (data.Name is {} name) {
query = query.Where(t => t.Name == name);
}
if (data.Age is > 0 age) {
query = query.Where(t => t.Age == age);
}
if (data.SortBy is not null) {
query = query.OrderBy(a => a.Something);
}

var things = await query.ToListAsync();
var query = _context.Things.AsQueryable();

if (data.Name is {} name) {
query = query.Where(t => t.Name == name);
}
if (data.Age is > 0 age) {
query = query.Where(t => t.Age == age);
}
if (data.SortBy is not null) {
query = query.OrderBy(a => a.Something);
}

var things = await query.ToListAsync();
Like this
Bread
Bread2y ago
Ahh, so build the queryable; then it is airquoteleft called airquoteright when you .ToListAsync()
Angius
Angius2y ago
Yep
Bread
Bread2y ago
Interesting!
Angius
Angius2y ago
.ToListAsync(), .FirstOrDefaultAsync(), CountAsync() etc. are where the query gets resolved
Bread
Bread2y ago
So I guess my current impl, is just executing the query then I'm transforming the shape of the data based on my signty
Angius
Angius2y ago
Your current code doesn't really do anything Since the query doesn't get modified in place You just call the .Where() on the query... and discard it
Bread
Bread2y ago
AwkwardKid
Angius
Angius2y ago
Good:
query = query.Where(...);
query = query.Where(...);
Bad:
query.Where(...);
query.Where(...);
Bread
Bread2y ago
Ahhhhh! So just update the query with it
Angius
Angius2y ago
All those methods — besides the ones that resolve the query — return an IQueryable, they're not void Yeah
Bread
Bread2y ago
Thanks!