The following query is not returning the proper results, it will return properly for company, but not the other two parameters. For clarification this is inside a post method of a page taking the user’s input for company, name, and/or state
var transporters = await _db.TransporterProfiles
.Include(x => x.TransportState)
.Where(x => x.Company == company || company == null &&
x => x.LastName == name || name == null &&
x => x.TransportState.Name == state || state == null)
.ToListAsync();
I’ve tried adding parentheses around each part of the query such as
.Where((x => x.Company == company || company == null) &&
(x => x.LastName == name || name == null) &&
(x => x.TransportState.Name == state || state == null))
but this produces an error
Operator ‘&&’ cannot be applied to operands of type ‘lambda expression’
2
Answers
There’s no reason to include
company == null
in the query. If you don’t want a search term, don’t include it at all. You can build AND conditions by addingWhere
clauses to a query as needed, eg :In the question’s case you can write something like this:
You don’t need to include
TransportState
to usex.TransportState.Name
in theWhere
clause.Include
is used to eagerly load related data, not tell EF to JOIN between related tables.If you don’t want
Include
you can start the query with :The issue with your syntax is you have multiple lambdas that should be one.
That said the actual solution is to do what @PanagiotisKanavos posted as an answer, generate the query dynamically based on the input values.