2010-01-21 37 views
3

爲什麼下面的LINQ to SQL語句會引發異常?爲什麼我不能在LINQ to SQL中重用函數

我有一個函數

bool TrimAndCompare(string s1, string s2) 
{ 
    return customer.CustomerID.Trim() == customerID.Trim() 
} 

...一些其他的功能,我所說的以上功能在我的LINQ聲明

var customers = from customer in _context.Customers 
          where 
           TrimAndCompare(customer.CustomerID, customerID) 
         select customer; 

以上的LINQ to SQL statment函數拋出一個異常 但下面不是爲什麼?

var customers = from customer in _context.Customers 
         where 
          customer.CustomerID.Trim() == customerID.Trim() 
         select customer; 

我得到的「System.NotSupportedException」 ,我嘗試訪問客戶

回答

8

在第二個片段,邏輯被翻譯成lambda表達式,然後將其編譯成一個表達式樹.. 。兩種查詢翻譯是:

_context.Customers 
     .Where(customer => TrimAndCompare(customer.CustomerID, customerID); 

VS

_context.Customers 
     .Where(customer => customer.CustomerID.Trim() == customerID.Trim()); 

LINQ to SQL知道如何處理表達式樹,它知道Trim以及字符串相等。它不知道知道如何處理你寫的任意方法的調用。

這種最簡單的方法可能是改變你的方法是:

Expression<Func<Customer, bool>> CustomerIdMatches(string customerID) 
{ 
    return customer => customer.CustomerID.Trim() == customerID.Trim() 
} 

然後,您可以使用:

from customer in context.Customers.Where(CustomerIdMatches(customerID)) 
... rest of query here 

或者你甚至可以製作自己的擴展方法做Where部分也是如此。

使它對於不同的領域更普遍的可重複使用有點棘手。特別是,查詢表達式不能很好地工作......這是可行的,但不是非常漂亮。

的使用會是這個樣子:

var query = context.Customers 
        .Where(TrimAndCompare(customer => customer.CustomerID, 
             customer => customerID)); 

不是非常好的:(

+0

好吧,如果我想要做的東西,是當我試圖讓一個布爾值回來,但什麼好的。像 變種客戶從客戶=在_context.Customers 其中 customer.GetID()==「一」 選擇顧客; – soldieraman 2010-01-21 08:07:29

+0

@soldierman:該點是一個'Where'表達式* *不返回一個布爾值你是compo se作爲查詢的一部分 - 注意我所有的例子都調用了Where。重點是它創建一個表達式樹,其中包含正確的邏輯,以便您可以將該表達式樹包含在查詢的其餘部分中。 – 2010-01-21 08:17:09

相關問題