3

EntityFrameworkLinqクエリの比較述語を一般的に作成する必要があります。リフレクションを使用しており、問題なく単一レベルのラムダ式を作成できます。しかし、私が行き詰まり始めているのは、関係のあるエンティティがあります

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」をReflectionに渡して、比較するラムダ式を作成し、item => item.Child.property == valueに似たラムダ式を作成するにはどうすればよいですか?

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 に答える