简体   繁体   中英

Advanced search with LINQ to EF

I have up to 4 values: string firstName, string lastName, string ssn, DateTime dateOfInjury. The user can enter any one of these or any combination. If they enter more than one, I want to return results using AND. For example, where firstName matches (if that's all they enter), or if firstName AND lastName match if they enter both of them, and so on. What's the best way to do this with LINQ? I'm hoping there's something more elegant that a giant switch statement.

I was planning on building the where clause dynamically, but it doesn't seem like that will work: Building dynamic where clauses in LINQ to EF queries .

Just build up your query. If you have a sequence of Where calls, those are AND'd together.

IQueryable<Customer> query = source.Customers;

if (firstName != null)
{
  query = query.Where(c => c.FirstName == firstName);
}
if (lastName != null)
{
  query = query.Where(c => c.LastName == lastName);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM