i'm using Dynamic Linq of Scott Gu and following this example:
Expression<Func<Customer, bool>> e1 = DynamicExpression.ParseLambda<Customer, bool>("City = \"London\"");
Expression<Func<Customer, bool>> e2 = DynamicExpression.ParseLambda<Customer, bool>("Orders.Count >= 10");
IQueryable<Customer> query = db.Customers.Where("@0(it) and @1(it)", e1, e2);
But in my case, i want to have dynamic variable of object.property in e1, e2... in where clause like this:
Expression<Func<Customer, bool>> e1 = DynamicExpression.ParseLambda<Customer, bool>("City = **[object.property]**");
i will be fill with value property of object at runtime
Can anyone please tell me how to do this?
Thanks
P/s: this can be done in case of expression:
var exp = "Person.Age = Persion1.Age";
var p = Expression.Parameter(typeof(Person), "Person");
var p1 = Expression.Parameter(typeof(Person1), "Person1");
var e = DynamicExpression.ParseLambda(new[] { p,p1 }, null, exp);
var result = e.Compile().DynamicInvoke(p,p1);
but i don't know how to do this in where clause.
Edit, as @pil0t: The answer for this case is using: Expression<Func<Customer, bool>> e1 = DynamicExpression.ParseLambda<Customer, bool>("Age > @0.Age",objPerson1);
Can I using something like Expression<Func<Customer, bool>> e1 = DynamicExpression.ParseLambda<Customer, bool>("Age > @Persion1.Age",objPerson1);
intead of @0. ?
If you goal is to get property value by name, you could simply use reflection:
object obj = new {MyProp = 123};
var valueOfDynamicProperty = obj.GetType().GetProperty("MyProp").GetValue(obj);
Expression<Func<Customer, bool>> e1 = DynamicExpression.ParseLambda<Customer, bool>("Age = @0", valueOfDynamicProperty);
For use property name in Dynamic expression it must be declared in type that you pass in ParseLambda, so:
object obj = new {MyProp = 123};
Expression<Func<Customer, bool>> e1 = DynamicExpression.ParseLambda<Customer, bool>("Age = @0.MyProp", obj);
will not work, but you can pass specific type:
public class MyClass
{
public int MyProperty {get;set;}
}
...
var obj = new MyClass {MyProperty = 123}; // obj is MyClass
Expression<Func<Customer, bool>> e1 = DynamicExpression.ParseLambda<Customer, bool>("Age = @0.MyProp", obj);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.