2010-01-21 61 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

相关问题