Write dynamic filter for Entity Framework Core

c# entity-framework-core linq

Question

I'm writing a small project use .net Core and Entity Framework.

I need implement dynamic filter for IQueryable<T>.

I have enums that define operators

public enum QueryOperatorEnums
{
   Equal = 0,
   NotEqual = 1,
   Constant = 2,
   LessThan = 3,
   GreaterThan = 4,
   LessThanOrEqual = 5,
   GreaterThanOrEqual = 6,
}  

And I have an extensions of IQueryable:

public static IQueryable<T> Filter<T>(this IQueryable<T> query, Dictionary<string, KeyValuePair<QueryOperatorEnums, object>> keyValuePairs)
{
    if (keyValuePairs == null)
        return query;

    foreach (var keyValuePair in keyValuePairs)
    {
        var propertyInfo = typeof(T).GetProperty(keyValuePair.Key);

        if (propertyInfo != null)
        {
            var operation = keyValuePair.Value;

            switch (operation.Key)
            {
                case QueryOperatorEnums.Constant:
                    break;

                case QueryOperatorEnums.Equal:
                    query = query.Where(obj => propertyInfo.GetValue(obj, null).Equals(operation.Value));
                    break;

                case QueryOperatorEnums.GreaterThan:
                    break;

                case QueryOperatorEnums.GreaterThanOrEqual:
                    break;

                case QueryOperatorEnums.LessThan:
                    break;

                case QueryOperatorEnums.LessThanOrEqual:
                    break;

                case QueryOperatorEnums.NotEqual:
                   break;

                default:
                    break;
            }
        }
    }

    return query;

}

What can I do to implement for special cases? Because property value is dynamic at run time. I can't detect type to use <=, >= ...

Thanks for your support

1
0
6/24/2019 8:11:34 AM

Expert Answer

As you have seen, you cannot use reflection.

However, 2 third-party libraries can help you with this

LINQ Dynamic

https://www.nuget.org/packages/System.Linq.Dynamic.Core/

The syntax required is a little bit different from C# but work great. It's the most popular library to do such a thing.


C# Eval Expression

Disclaimer: I'm the owner of the project C# Eval Expression

The library is not free, but you can do pretty much any dynamic LINQ using the same syntax as C#.

So you will be able to build a string to evaluate and the library will do the rest for you.

Here are some example using EF Classic:

Has Dynamic linq work with MySql, Sql Server and Postgresql, Jonathan?

Yes, I don't see why it could not work. Under the hood, is generate LINQ expression as you could call by hand.

1
3/29/2019 4:57:32 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow