WhereIn with dynamic property

I want to build LINQ, which will later be transferred WHERE INto sql. In the normal case, I would do:

( querableis IQuerable<T>and arris IEnumerable<int>)

querable = querable.Where(e => arr.Contains(e.Id));

BUT

My problem is that the value I want to filter ( e.Id) is dynamic, and I get it as a string. How can i do this?

A little more background: I am making a REST API endpoint at which the user can send by which column he wants to filter the values, so examples will be:

  • filter: {"id": [1,2]}

What I want to translate into something like queryable.Where(e => new [] {1,2}.Contains(e.Id))

  1. filter: {"customerId": [4,5]}

What I want to translate into something like queryable.Where(e => new [] {4,5}.Contains(e.CustomerId))

So basically my input is a column name, which is stringalso a list of identifiers, whichIEnumerable<int>

, Expression ( ), , .

+4
1

:

public static class QueryableExtensions {
    public static IQueryable<TEntity> WhereIn<TEntity, TValue>(this IQueryable<TEntity> query, string property, IEnumerable<TValue> values) {
        // x
        var arg = Expression.Parameter(typeof(TEntity), "x");
        // x.Property            
        var prop = Expression.Property(arg, property);
        // values.Contains(x.Property)
        var contains = Expression.Call(
            typeof(Enumerable),
            "Contains",
            new[] { typeof(TValue) },
            Expression.Constant(values),
            prop
        );
        // x => values.Contains(x.Property)
        var lambda = Expression.Lambda<Func<TEntity, bool>>(contains, arg);
        return query.Where(lambda);
    }
}

, , (, int-pass array ints).

+2

Source: https://habr.com/ru/post/1690715/


All Articles