C
Join ServerC#
help
How do I 'build' a QUERY with EF Core?
BBread8/20/2022
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?

AAngius8/20/2022
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();
AAngius8/20/2022
Like this
BBread8/20/2022
Ahh, so build the queryable; then it is
called
when you


.ToListAsync()
AAngius8/20/2022
Yep
BBread8/20/2022
Interesting!
AAngius8/20/2022
.ToListAsync()
, .FirstOrDefaultAsync()
, CountAsync()
etc. are where the query gets resolvedBBread8/20/2022
So I guess my current impl, is just executing the query then I'm transforming the shape of the data based on my rules?
BBread8/20/2022

AAngius8/20/2022
Your current code doesn't really do anything
AAngius8/20/2022
Since the query doesn't get modified in place
AAngius8/20/2022
You just call the
.Where()
on the query... and discard itBBread8/20/2022

AAngius8/20/2022
Good:
Bad:
query = query.Where(...);
Bad:
query.Where(...);
BBread8/20/2022
Ahhhhh! So just update the query with it
AAngius8/20/2022
All those methods — besides the ones that resolve the query — return an
IQueryable
, they're not void
AAngius8/20/2022
Yeah
BBread8/20/2022
Thanks!