0

我正在使用 Scott Gu 的 Dynamic Linq 并遵循以下示例:

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);

但在我的情况下,我想在 e1、e2... 中有 object.property 的动态变量,在 where 子句中是这样的:

Expression<Func<Customer, bool>> e1 = DynamicExpression.ParseLambda<Customer, bool>("City = **[object.property]**");

我将在运行时填充对象的 value 属性

谁能告诉我该怎么做?

谢谢

P / s:这可以在表达式的情况下完成:

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);

但我不知道如何在 where 子句中执行此操作。

编辑,如@pil0t:这种情况的答案是使用:Expression<Func<Customer, bool>> e1 = DynamicExpression.ParseLambda<Customer, bool>("Age > @0.Age",objPerson1);

我可以使用Expression<Func<Customer, bool>> e1 = DynamicExpression.ParseLambda<Customer, bool>("Age > @Persion1.Age",objPerson1);@0 之类的东西吗??

4

1 回答 1

0

如果您的目标是按名称获取属性值,则可以简单地使用反射:

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);

要在动态表达式中使用属性名称,它必须以您在 ParseLambda 中传递的类型声明,因此:

object obj = new {MyProp = 123};
Expression<Func<Customer, bool>> e1 = DynamicExpression.ParseLambda<Customer, bool>("Age = @0.MyProp", obj);

将不起作用,但您可以传递特定类型:

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);
于 2013-11-05T11:41:55.860 回答