LINQ to SQL:如果数据库没有返回值,则Count()会抛出异常

sol*_*man 1 .net c# null linq-to-sql

我有一个linq to sql语句,它将一组Customer详细信息返回给客户对象

var customers = from .....
Run Code Online (Sandbox Code Playgroud)

然后我用

if(customers.Count() > 0)
{
    return customers.First();
}
else
{
    return null;
}
Run Code Online (Sandbox Code Playgroud)

但是customers.Count()会抛出一个

'customers.Count()' threw an exception of type 'System.NotSupportedException'   int {System.NotSupportedException}
Run Code Online (Sandbox Code Playgroud)

我怎么能检查是否有任何退货???

=============

这就是问题所在.这实际上是我在LINQ语句中遇到的一个问题

我有一个功能

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

var customers = from customer in _context.Customers
                          where
                                TrimAndCompare(customer.CustomerID, customerID)
                          select customer;
Run Code Online (Sandbox Code Playgroud)

当我这样做时,一切都很好

var customers = from customer in _context.Customers
                          where
                                customer.CustomerID.Trim() == customerID.Trim()
                          select customer;
Run Code Online (Sandbox Code Playgroud)

猜猜你不能在LINQ语句中重用函数

dtb*_*dtb 6

您不能在Linq-To-SQL表达式中使用SQL中没有等效项的方法.


为了测试结果,不要使用CountFirst,因为这会执行两次SQL查询.
相反,使用FirstOrDefault:

return customers.FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

FirstOrDefault返回第一个元素,如果没有找到元素,返回null: