2

How to build a query like the selectbyexample using linq-to-entities?

For example:

public class Person
{
      public string Name {get; set;}
      public int Age {get; set;}
      public string City {get; set;}
}

If I had a new Person() with all properties with values are null, the query should return me all the records of the Person table.

But if I pass an object with the property Age = 25, the query should return me all records with age = 25;

I would like to build a single query filter to accept any of the properties and if one were to disregard it null.

Vinicius Saeta
  • 183
  • 1
  • 2
  • 13

3 Answers3

1

First of all your example cannot have all properties null because Age is not nullable.

Anyway it is done this way:

public static IQueryable<Person> QueryByExample(Person example, YourContext context)
{
    var query = context.Persons;

    if (example.Name != null) 
    {
       string name = example.Name;
       query = query.Where(p => p.Name == name);
    }

    // Same for other properties

    return query;
}
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
1
       var p = new Person {Age = 25};

       src.Where(el => p.Age == null ? true : el.Age == p.Age)
           .Where(el => p.Name == null ? true : el.Name == p.Name)
           .Where(el => p.City == null ? true : el.City == p.City);

in your Person class, Age should be nullable (int? instead of int).

Harps
  • 640
  • 8
  • 17
0

You need a custom Linq method. Here is how you can do it :

http://msdn.microsoft.com/en-us/library/cc981895.aspx

This can help you on how to iterate through your class properties dynamically

c# - How to iterate through classes fields and set properties

Community
  • 1
  • 1
Paweł Staniec
  • 3,151
  • 3
  • 29
  • 41