开发者

Dynamic Lambda with all properties of a property of an object

I had asked a question on how to dynamically compile a LINQ query with all the properties of an object and houlgap had been kind enough to give me the following code

    private static Func<MyEntity, bool> GenerateLambda(MyEntity _myEntity, PropertyInfo propertyInfo)
{
    var instance = Expression.Parameter(propertyInfo.DeclaringType, "i");
    var property = Expression.Property(instanc开发者_开发技巧e, propertyInfo);
    var propertyValue = Expression.Constant(propertyInfo.GetValue(_myEntity, null));
    var equalityCheck = Expression.Equal(property, propertyValue);
    return Expression.Lambda<Func<MyEntity, bool>>(equalityCheck, instance).Compile();
}

This works great if the property to be queried is directly a member of the object but for me there is an intermediate property in between. For e.g. The Func Delegate is for another type e.g. Func<ABCMyEntity,bool> while the MyEntity is a member of this object (ABCMyEntity.MyEntity). The Propertyinfo object which is passed is a member of MyEntity.

I know it sounds terribly confusing but I am not able to better explain it. (Maybe because I am not a native speaker). Please ask me if something is not clear in the question.

It is continued from Constructing Dynamic LINQ queries with all properties of an object


If you need to access a chain of properties (e.g. v.MyEntity.OtherProperty) then you can just call Expression.Property multiple times:

var prop1 = // first property
var prop2 = // second property

// Variable has type of the declarating type of the 1st property
var instance = Expression.Parameter(prop1.DeclaringType, "i"); 

// Get first property on the 'instance'
var expr1 = Expression.Property(instance, prop1); 
// Get second property on the previous expression
var expr2 = Expression.Property(expr, prop2); 

// The rest of the code stays the same (only use 'expr2')
var propertyValue = Expression.Constant(propertyInfo.GetValue(_myEntity, null)); 
var equalityCheck = Expression.Equal(expr2, propertyValue); 
return Expression.Lambda<Func<MyEntity, bool>>
  (equalityCheck, instance).Compile(); 

If you need to access more than just two properties, you can easily turn the part that calls Expression.Property into a loop - you would just iterate over a list of desired properties and add property access to the expression using Expression.Property.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜