2015-04-27 49 views
1

因此,我試圖構建一個通用表達式,它從IQueryable中獲取Datetime屬性,並對其應用Day比較。但是,我不斷收到錯誤提供的參數數量不正確。Linq表達式構建爲lambda聲明提供的參數數量不正確

我的功能看起來是這樣的:

public IQueryable<T> SetDateCompare<T>(IQueryable<T> OriginalQuery, Expression<Func<T, DateTime>> getDateFunc, DateTime ComparisonDate, bool isGreaterThan = true) 
    where T : class 
    { 
     if (isGreaterThan) 
     { 

      Expression left = Expression.Call(getDateFunc.Body, typeof(DateTime).GetMethod("get_Day")); 
      Expression right = Expression.Constant(ComparisonDate.Day, typeof(int)); 
      Expression res = Expression.GreaterThan(left, right); 

      //var whereCall = Expression.Lambda<Func<T,bool>>(Expression.GreaterThanOrEqual(left, right),). 

      MethodCallExpression whereCall = Expression.Call(typeof(Queryable), 
                    "Where", 
                    new Type[] { OriginalQuery.ElementType }, 
                    OriginalQuery.Expression, 
                    Expression.Lambda<Func<string, bool>>(res), getDateFunc.Parameters.Single()); 

      OriginalQuery.Provider.CreateQuery<T>(whereCall); 
     } 

     return OriginalQuery; 

    } 

有誰知道我能做些什麼來解決這個問題?

回答

1

嘗試修復這樣的代碼:

public IQueryable<T> SetDateCompare<T>(IQueryable<T> OriginalQuery, Expression<Func<T, DateTime>> getDateFunc, DateTime ComparisonDate, bool isGreaterThan = true) 
where T : class 
    { 
     if (isGreaterThan) 
     { 

      Expression left = Expression.Call(getDateFunc.Body, typeof(DateTime).GetMethod("get_Day")); 
      Expression right = Expression.Constant(ComparisonDate.Day, typeof(int)); 
      Expression res = Expression.GreaterThan(left, right); 

      var whereCallLambda = Expression.Lambda<Func<T, bool>>(Expression.GreaterThanOrEqual(left, right), getDateFunc.Parameters.Single()); 

      MethodCallExpression whereCall = Expression.Call(typeof(Queryable), 
                    "Where", 
                    new Type[] { OriginalQuery.ElementType }, 
                    OriginalQuery.Expression, 
                    whereCallLambda); 

      OriginalQuery = OriginalQuery.Provider.CreateQuery<T>(whereCall); 
     } 

     return OriginalQuery; 

    } 
+0

甜這樣可以解決問題,但現在我得到另一個錯誤 –