2014-12-13 127 views
1

我正在尝试为运行时创建的表生成Lambda表达式。 的表达是建立正常,但当我打电话编译()方法,我得到这个错误 “类型‘cseval.Item’的ParameterExpression不能被用于类型‘System.Object的’的委托参数” 这是我的功能动态对象的Lambda表达式

public Func<dynamic, Boolean> GetWhereExp(List<WhereCondition> SearchFieldList, dynamic item) 
    { 

     ParameterExpression pe = Expression.Parameter(item.GetType(), "c"); 

     Expression combined = null; 

     if (SearchFieldList != null) 
     { 
      foreach (WhereCondition fieldItem in SearchFieldList) 
      { 
       //Expression for accessing Fields name property 
       Expression columnNameProperty = Expression.Property(pe, fieldItem.ColumName); 


       //the name constant to match 
       Expression columnValue = Expression.Constant(fieldItem.Value); 

       //the first expression: PatientantLastName = ? 
       Expression e1 = Expression.Equal(columnNameProperty, columnValue); 

       if (combined == null) 
       { 
        combined = e; 
       } 
       else 
       { 
        combined = Expression.And(combined, e); 
       } 
      } 
     } 
     var result = Expression.Lambda<Func<dynamic, bool>>(combined, pe); 
     return result.Compile(); 
    } 
+0

我不相信'dynamic'被允许在'Expression's。我没有看到代码中的任何东西看起来像是实际上需要'动态'类型。你试过用'object'代替'dynamic'吗? – 2014-12-13 08:51:19

+0

是的,我已经尝试过,但同样的错误。 – Bakri 2014-12-13 08:58:05

回答

2

我已经改变了动态仿制药,此代码的工作对我来说:

public Func<T, Boolean> GetWhereExp<T>(List<WhereCondition> SearchFieldList, T item) 
    { 
     var pe = Expression.Parameter(item.GetType(), "c"); 
     Expression combined = null; 
     if (SearchFieldList != null) 
     { 
      foreach (var fieldItem in SearchFieldList) 
      { 
       var columnNameProperty = Expression.Property(pe, fieldItem.ColumName); 
       var columnValue = Expression.Constant(fieldItem.Value); 
       var e1 = Expression.Equal(columnNameProperty, columnValue); 
       combined = combined == null ? e1 : Expression.And(combined, e1); 
      } 
     } 
     var result = Expression.Lambda<Func<T, bool>>(combined, pe); 
     return result.Compile(); 
    } 

小的话:你的方法返回的功能,而不是表达,故得名“GetWhereExp”稍有不正确。如果你想返回函数,恕我直言,最好使用反射。

UPD:我用这个代码来测试:

  var expressions = new List<WhereCondition> 
       { 
        new WhereCondition("Column1", "xxx"), 
        new WhereCondition("Column2", "yyy"), 
       }; 

      var item = new 
       { 
        Column1 = "xxx", 
        Column2 = "yyy" 
       }; 

      var func = LinqExpr.GetWhereExp(expressions, (dynamic)item); 

      Console.WriteLine(new[] {item}.Count(a => func(a))); 
+0

这里的问题该项目类型是在运行时生成的。 所以当我需要调用函数我不能通过类型为T参数 – Bakri 2014-12-13 09:00:27

+0

请参阅更新,是否可以投与动态? – omikad 2014-12-13 09:03:07