2014-12-13 64 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