使用Expression.Parameter中的子属性来构建linq表达式

时间:2016-10-17 15:28:59

标签: c# recursion lambda linq-expressions

我们假设我们有以下正常表达式:

var result = SomeList.Where(item => item.Status.Description.Contains("READY"));

对于这些对象:

public class Movie
{
    public MovieStatus Status {get; set;}
}
public class MovieStatus
{
    public string Description {get; set;}
}

这不起作用:

ParameterExpression pe = Expression.Parameter(typeof(T), "item.Status");
MemberExpression propExp = Expression.Property(pe, "Description");//boem! Description is not a property of T.

使用T属性进行一些递归,我可以得到正确的MemberExpression,并且在调试时看起来没问题,最后我有这个lambda表达式:

  

{item => item.Status.Description.Contains(" READY")}

并且,将这些表达式应用于IQueryable列表时,结果就是:

  

{System.Collections.Generic.List`1 [Movie] .Where(item => item.Status.Description.Contains(" READY"))}

看起来没问题,但是当编译/执行列表中的表达式时,它会给我以下错误:

  

其他信息:变量" item.Status'类型' MovieStatus'引用范围'',但未定义

我如何需要一种链条' ParameterExpression获取上述lambda表达式?

实际代码没有这些固定变量,它是具有任何子属性的任何对象使用的通用实现。输入是正常格式XX.YY的属性名称和比较值。发布所有代码有点大,但下面是其中的一个子集,带走所有递归以关注问题。递归的一些结果在这里已被硬编码。此外,它并不总是Contains

    public static void Test<T>(IQueryable<T> source)
    {
        string propertyName = "Status.Description";
        string value = "READY";
        ParameterExpression pe = Expression.Parameter(typeof(T), "item");
        Type type = typeof(T).GetProperty("Status").PropertyType;//property name is some recursion result

        ParameterExpression peSub = Expression.Parameter(type, "item.Status");
        MemberExpression propExp = Expression.Property(peSub, "Description");
        Expression whereValue = GetValueExpression(value, type);

        //do the contains rule expression
        Type subType = type.GetProperty("Description").PropertyType;//property name is also recursion result
        MethodInfo containsMethod = typeof(string).GetMethod("Contains", new[] { subType });
        Expression ruleExpression = Expression.Call(propExp, containsMethod, whereValue);

        //create source.Where([expressions])
        Type[] elementTypes = new Type[] { source.ElementType };

        Expression<Func<T, bool>> labdaExpression = Expression.Lambda<Func<T, bool>>(ruleExpression, new ParameterExpression[] { pe });

        //method call expression
        Expression whereCallExpression = Expression.Call(typeof(Queryable), "Where",
        elementTypes, source.Expression, labdaExpression);

        source = source.Provider.CreateQuery<T>(whereCallExpression);
        source.ToList();//boom, error: Additional information: variable 'item.Status' of type 'MovieStatus' referenced from scope '', but it is not defined
    }

1 个答案:

答案 0 :(得分:4)

where子句中只有一个参数。让我们先创建:

public static IQueryable<T> Where<T>(this IQueryable<T> query, string selector, string comparer, string value)
{
    var target = Expression.Parameter(typeof(T));

    return query.Provider.CreateQuery<T>(CreateWhereClause(target, query.Expression, selector, comparer, value));
}

对于我们需要创建该子句的参数,实际上是一个调用表达式,它“引用”实际的lambda:

static Expression CreateWhereClause(ParameterExpression target, Expression expression, string selector, string comparer, string value)
{
    var predicate = Expression.Lambda(CreateComparison(target, selector, comparer, value), target);

    return Expression.Call(typeof(Queryable), nameof(Queryable.Where), new[] { target.Type },
        expression, Expression.Quote(predicate));
}

lambda表达式应包含实际比较,其中包含左侧的成员访问权限和右侧的实际值:

static Expression CreateComparison(ParameterExpression target, string selector, string comparer, string value)
{
    var memberAccess = CreateMemberAccess(target, selector);
    var actualValue = Expression.Constant(value, typeof(string));

    return Expression.Call(memberAccess, comparer, null, actualValue);
}

对于成员访问,我们可以链接这些属性表达式:

static Expression CreateMemberAccess(Expression target, string selector)
{
    return selector.Split('.').Aggregate(target, (t, n) => Expression.PropertyOrField(t, n));
}

最后,你应该能够:

query.Where("Status.Description", "Contains", "READY");

BTW,我刚刚简化了this code,希望能提供相应的答案。