2013-01-03 75 views
1

首先,作爲該問題的一般概述,我正在編寫一個MVC Web應用程序,以便根據幾種不同的業務邏輯規則查詢我的存儲庫。用戶首先將文本輸入到網頁中,並且將在我的業務層中解析所述文本,並將相應的where子句查詢發送到存儲庫。將變量值分配給lambda表達式以傳遞到存儲庫方法

所以,我的代碼示例:

public Document GetDocuments(string txtFilter) 
{ 
    string [] filterVals = // do some business logic here to parse txtFilter into the filterValsArray 

    // filterQuery will utlimately contain the where clause for the repository 
    Expression<Func<DocumentListViewModel, bool>> filterQuery = null; 

    // case 1, when filterVals has only 1 value: 
    if (filterVals[0].Length == 1) 
    { 
     filterQuery = x => x.SomeField == filterVals[0]; 
    } 
    else // assign filterQuery to another set of expressions 

    // repository call 
    return _unitOfWork.DocumentRepository.Get(filterQuery); 
} 

當我運行它,我得到一個運行時異常「不能調用非委託類型。」我相信正在發生的事情(當然,如果我對此有錯誤,請糾正),實際表達式是在存儲庫中枚舉的,此時filterVals不再處於範圍之內。所以...有沒有辦法將這些值放到我的where子句表達式中?任何幫助將不勝感激。

+0

@MFFOX:抱歉,今天早上很累。我已經解決了我的問題,謝謝你指出。 – sovemp

回答

1

嘗試改變

Expression<Func<DocumentListViewModel, bool>> filterQuery = null; 

Func<DocumentListViewModel, bool> filterQuery = null; 

,看看會發生什麼。

+0

或者,在它們上面調用'Compile'。 :) – JerKimball

+0

或者不要在不需要時使用表達式。 ;) –

+0

謝謝,我的好先生! – JerKimball

0

我假設你正在編譯文檔庫中的表達式?如果沒有你需要的參數調用編譯()

相關問題