Search code examples
c#entity-framework

Entity Framework: How can I get entities from a table with several conditions


It's rather easy to get persons with the names 'Peter', 'Paul' and 'Jeff'

var persons = await context.Persons.Where(p => nameList.Contains(p.Name)).ToArrayAsync();

And it's also easy to get all persons named 'Jeff' from Springfield with blonde hair.

var persons = await context.Persons.Where(p => 
   p.Name == 'Jeff' && p.City == 'Springfield' && p.Hair == 'blonde').ToArrayAsync();

But imagine I have a list of let's n persons without any information of a primary key. I can determine them by name, city and hair color? How do I express a single linq query to get this data? Or do I have to ask the DB again and again and again?


Solution

  • You can do this using the or operator (||):

    var persons = await context.Persons.Where(p => 
       (p.Name == 'Jeff' && p.City == 'Springfield' && p.Hair == 'blonde')
       || (p.Name == 'Tom' && p.City == 'New York' && p.Hair == 'black')
       || (p.Name == 'Tim' && p.City == 'Chicago' && p.Hair == 'ginger'))
       .ToArrayAsync();