【发布时间】:2010-11-16 14:20:24
【问题描述】:
我问了一个关于如何使用对象的所有属性动态编译 LINQ 查询的问题,并且 houlgap 很友好地给了我以下代码
private static Func<MyEntity, bool> GenerateLambda(MyEntity _myEntity, PropertyInfo propertyInfo)
{
var instance = Expression.Parameter(propertyInfo.DeclaringType, "i");
var property = Expression.Property(instance, propertyInfo);
var propertyValue = Expression.Constant(propertyInfo.GetValue(_myEntity, null));
var equalityCheck = Expression.Equal(property, propertyValue);
return Expression.Lambda<Func<MyEntity, bool>>(equalityCheck, instance).Compile();
}
如果要查询的属性直接是对象的成员,但对我来说中间有一个中间属性,这很有效。例如Func Delegate 适用于另一种类型,例如Func<ABCMyEntity,bool> 而 MyEntity 是此对象 (ABCMyEntity.MyEntity) 的成员。传递的 Propertyinfo 对象是 MyEntity 的成员。
我知道这听起来很令人困惑,但我无法更好地解释它。 (也许是因为我不是母语人士)。请问我问题中是否有不清楚的地方。
从Constructing Dynamic LINQ queries with all properties of an object继续
【问题讨论】:
标签: c# .net linq reflection linq-to-entities