具有嵌套属性的动态linq表达式树

时间:2016-11-01 15:33:07

标签: c# entity-framework linq linq-expressions expressionbuilder

我有一个列表,我必须过滤子属性。过滤器运算符是动态的,我使用谓词构建器来组合多个过滤器/ lambdas。

为简单起见,我们假设我有两个类:

public class FirstClass
{
    public int Id { get; set; }
    public ICollection<SecondClass> MyList { get; set; }
}

public class SecondClass
{
    public int ReferenceId { get; set; }
    public int Value { get; set; }
}

我的过滤器使用引用ID,运算符类型和值,这样伪代码就像这样:

"list of FirstClass".Where(param1 => 
    param1.MyList.Single(param2 => 
        param2.ReferenceId == "reference id").Value "operatorType" "value")

实际过滤器类似于123 eq 456,其中引用ID为123,operatorType为&#34; eq&#34;价值是456。

如果操作员只是平等,那么以下工作就可以了:

Expression<Func<FirstClass, bool>> lambda = 
    param1 => param1.MyList.Single(param2 => param2.ReferenceId == id).Value == value;

此外,仅使用动态表达式对FirstClass进行过滤,就像魅力一样,例如过滤ID(我的ExpressionTypeDictionary是一个字典,用于根据提供的ExpressionType选择operatorType):

var parameter = Expression.Parameter(typeof(FirstClass), "param1");
Expression body = parameter;
body = Expression.Property(body, "Id");
body = Expression.MakeBinary(ExpressionTypeDictionary[operatorType], body, value);
var lambda = Expression.Lambda<Func<FirstClass, bool>>(body, new[] { parameter });

我能够进行以下编译,但使用EF Core对实际数据执行过滤器会返回querySource的异常:

var parameter = Expression.Parameter(typeof(FirstClass), "param1");
Expression<Func<FirstClass, int>> left = param1 => 
    param1.MyClass.Single(param2 => param2.ReferenceId == id).Value;
var body = Expression.MakeBinary(
    ExpressionTypeDictionary[operatorType], 
    left.Body, 
    Expression.Constant(value));
var lambda = Expression.Lambda<Func<FirstClass, bool>>(body, new[] { parameter });
...
theList.Where(lambda);

任何建议都表示赞赏:)

1 个答案:

答案 0 :(得分:6)

我认为而不是像这样表达

Expression<Func<FirstClass, bool>> predicate = 
    x => x.MyList.Single(y => y.ReferenceId == id).Value [operator] value;

你最好建立一个这样的表达式:

Expression<Func<FirstClass, bool>> predicate = 
    x => x.MyList.Any(y => y.ReferenceId == id && y.Value == value);

以下是如何做到这一点:

var innerParameter = Expression.Parameter(typeof(SecondClass), "y");
var innerPredicate = Expression.Lambda<Func<SecondClass, bool>>(
    Expression.AndAlso(
        Expression.Equal(Expression.Property(innerParameter, "ReferenceId"), Expression.Constant(id)),
        Expression.MakeBinary(ExpressionTypeDictionary[operatorType], Expression.Property(innerParameter, "Value"), Expression.Constant(value))),
    innerParameter);
var parameter = Expression.Parameter(typeof(FirstClass), "x");
var predicate = Expression.Lambda<Func<FirstClass, bool>>(
    Expression.Call(
        typeof(Enumerable), "Any", new Type[] { typeof(SecondClass) },
        Expression.Property(parameter, "MyList"), innerPredicate),
    parameter);