Filter Entity model by any property and value dynamically passed

Viewed 798

I have more than 1 Entity framework Model related to patients.

Now i want to Filter records by Some List of Property value.

I will passed List to on which filed i need to apply filter that is dynamically.

Ex: Class with 2 Properties 1) PropertyName & 2) FilterValue

I will pass List of values in below format Row1) "TableName.PropertyName" & Value = "value to filter" Row1) "TableName.PropertyName" & Value = "value to filter" etc...

So i don't know in advance which filed i need to apply filter its dynamically decided and it may be for multiple properties.

2 Answers

When speaking of dynamic for Entity Framework, there is often 2 easy solutions (one free, one paid).

For both solutions, you will need to build a string containing your dynamic projection.

Free

LINQ Dynamic: https://github.com/StefH/System.Linq.Dynamic.Core

A very popular library that allows easily to handle this scenario

var query = context.Customers.Where("City == @0", "London");

I recommend this library if you want to handle most basic scenario

Paid

Disclaimer: I'm the owner of the project Eval-Expression.NET

This library is more powerful by using Expression Tree. It supports exactly the same syntax as C#

var query = context.Customers.Where(c => "c.City < @0", "London");
var query = context.Customers.Where(c => "c.City < city", new { city = "London"});
var query = context.Customers.Where(c => "c.City < city", entityWithCityProperty);

This library can be used for more complex scenarios. It let you compile and execute dynamic C# code at runtime.

You can achieve that using reflection, but be aware that it will be slow on a large dataset.

the output for the following code is : Name: John, Age: 24

class Patient 
{
    public int Age { get; set; }    

    public string Name { get; set; }
}

static void Main(string[] args)
{
    var patients = new List<Patient> {
        new Patient { Age = 24, Name = "John"},
        new Patient { Age = 36, Name = "Johny"},
        new Patient { Age = 24, Name = "Jonas"},
        new Patient { Age = 18, Name = "John"},
    };

    var filters = new Dictionary<string,object>();
    filters.Add("Age", 24);
    filters.Add("Name", "John");

    var query = patients.AsQueryable();
    foreach (var filter in filters)
    {
        query = query.Where(p => p.GetType().GetProperty(filter.Key).GetValue(p, null).ToString() == filter.Value.ToString());
    }

    foreach (var patient in query.ToList())
    {
        System.Console.WriteLine($"Name: {patient.Name}, Age: {patient.Age}");                
    }

}
Related