C
C#3y 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
Angius3y 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
BreadOP3y ago
Ahh, so build the queryable; then it is airquoteleft called airquoteright when you .ToListAsync()
Angius
Angius3y ago
Yep
Bread
BreadOP3y ago
Interesting!
Angius
Angius3y ago
.ToListAsync(), .FirstOrDefaultAsync(), CountAsync() etc. are where the query gets resolved
Bread
BreadOP3y 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
Angius3y 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
BreadOP3y ago
AwkwardKid
Angius
Angius3y ago
Good:
query = query.Where(...);
query = query.Where(...);
Bad:
query.Where(...);
query.Where(...);
Bread
BreadOP3y ago
Ahhhhh! So just update the query with it
Angius
Angius3y ago
All those methods — besides the ones that resolve the query — return an IQueryable, they're not void Yeah
Bread
BreadOP3y ago
Thanks!
Want results from more Discord servers?
Add your server