skip to Main Content

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


  1. 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 adding Where clauses to a query as needed, eg :

    if(value1 != null)
    {
        query=query.Where(x=>x.Property1 == value1);
    }
    if(value2 != null)
    {
        query=query.Where(x=>x.Property2 == value2);
    }
    

    In the question’s case you can write something like this:

    var query=_db.TransporterProfiles.Include(x => x.TransportState).AsQueryable();
    if(company!=null)
    {
        query=query.Where(x => x.Company == company);
    }
    if(name!=null)
    {
        query=query.Where(x => x.LastName == name);
    }
    if(state!=null)
    {
        query=query.Where(x => x.TransportState.Name == state);
    }
    
    var transporters=await query.ToListAsync();
    

    You don’t need to include TransportState to use x.TransportState.Name in the Where 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 :

    var query=_db.TransporterProfiles.AsQueryable();
    
    Login or Signup to reply.
  2. The issue with your syntax is you have multiple lambdas that should be one.

    .Where(x => (x.Company == company || company == null) &&
       (x.LastName == name || name == null) &&
       (x.TransportState.Name == state || state == null))
    

    That said the actual solution is to do what @PanagiotisKanavos posted as an answer, generate the query dynamically based on the input values.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search