3

我必须一般为实体框架 Linq 查询构建一个比较谓词。我正在使用反射,并且能够毫无问题地构建单级 Lambda 表达式。但是,我开始陷入困境的地方是我有一个有关系的实体

public class Parent {
    public virtual Child child { get; set; }
    .... Other Stuff...
}

public class Child {
    public int property { get; set; }
    public virtual Parent parent { get; set; }
    .... Other Stuff.....
}

我怎样才能将“Child.property”传递给反射,以便能够创建一个 lambda 表达式进行比较并得出一个类似于 item => item.Child.property == value 的 lambda 表达式?

4

2 回答 2

3

我假设您想要一个支持嵌套属性的通用解决方案:

public Expression buildLambda(Type startingType, string propertyPath, object value) {

  var parameter=Expression.Parameter(startingType,"item");
  var valueExpression = Expression.Constant(value);
  var propertyExpression=propertyPath.Split('.').Aggregate(parameter,(Expression parent,string path)=>Expression.Property(parent,path));
  return Expression.Lambda(Expression.Equal(propertyExpression,valueExpression),parameter);
}
于 2012-11-05T18:04:11.807 回答
3

我想你正在寻找这个:

ParameterExpression parameter = Expression.Parameter(typeof(Parent), "item");
Expression child = Expression.PropertyOrField(parameter, "child");
Expression childProperty = Expression.PropertyOrField(child, "property");
int value = 1;
Expression comparison = Expression.Equal(childProperty, Expression.Constant(value));

Expression<Func<Parent, bool>> lambda = Expression.Lambda<Func<Parent, bool>>(comparison, parameter);


var sample = new[] { new Parent() { child = new Child() { property = 1 } } };
var result = sample.Where(lambda.Compile());
于 2012-11-05T17:52:55.587 回答