-->

LINQ Expression for Contains

2019-04-09 00:32发布

问题:

I want to add dynamic expression in linq but facing issues on contains method it is working perfectly for Equal method

Problem is i'm getting FilterField dynamically how to replace in query

So far i had tried

List<int> Ids = new List<int>();  
**string filterField ="DEPARTMENT"; ==> Dynamic Field**

var eParam = Expression.Parameter(typeof(EmployeeDetail), "e");

var comparison = Expression.Equal(Expression.Property(eParam, filterField), Expression.Convert(Expression.Constant(Ids), Expression.Property(eParam, filterField).Type));

var lambda = Expression.Lambda<Func<EmployeeDetail, bool>>(comparison, eParam);

var countMonthly1 = ctx.tblMonthlyInput.Join(ctx.tblEmployee, a => a.CompanyId, b => b.CompanyId, (a, b) => b).Where(lambda).Count();

I want to make above query works for Contains method using linq expression

sample query :

var countMonthly = (from a in ctx.tblMonthlyInput
                    join b in ctx.tblEmployee on a.CompanyId equals b.CompanyId
                    where categoryId.Contains(a.CategoryId)  //want to make this dynamic
                    select a).Count() == 0;

回答1:

This will work for you:

void Main()
{
    var filterField = "Id";
    List<int> Ids = new List<int>();
    var eParam = Expression.Parameter(typeof(EmployeeDetail), "e");
    var method = Ids.GetType().GetMethod("Contains");
    var call = Expression.Call(Expression.Constant(Ids), method, Expression.Property(eParam, filterField));
    var lambda = Expression.Lambda<Func<EmployeeDetail, bool>>(call, eParam);
}

public class EmployeeDetail
{
    public int Id { get; set; }
}

First, you look for the Contains method on the type of Ids. Then we simply invoke it with Ids as the instance, and the property as the argument