Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# LINQ to SQL:如果数据库不返回值,Count()将引发异常_C#_.net_Linq To Sql_Null - Fatal编程技术网

C# LINQ to SQL:如果数据库不返回值,Count()将引发异常

C# LINQ to SQL:如果数据库不返回值,Count()将引发异常,c#,.net,linq-to-sql,null,C#,.net,Linq To Sql,Null,我有一个linq to sql语句,它将一组客户详细信息返回给客户对象 var customers = from ..... 然后我使用 if(customers.Count() > 0) { return customers.First(); } else { return null; } 但是客户。Count() 抛出 'customers.Count()' threw an exception of type 'System.NotSupportedExcepti

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

var customers = from .....
然后我使用

if(customers.Count() > 0)
{
    return customers.First();
}
else
{
    return null;
}
但是客户。Count() 抛出

'customers.Count()' threw an exception of type 'System.NotSupportedException'   int {System.NotSupportedException}
否则我如何检查是否没有归还物品

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

这就是问题所在。这实际上是我的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;
当我这么做的时候,一切都很好

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

我猜您不能在LINQ语句中重用函数,那么您就不能在LINQ To SQL表达式中使用SQL中没有等价项的方法


为了测试结果,不要使用Count和First,因为这会执行SQL查询两次。
相反,请使用FirstOrDefault:


返回第一个元素,如果找不到元素,则返回null:

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


为了测试结果,不要使用Count和First,因为这会执行SQL查询两次。
相反,请使用FirstOrDefault:


返回第一个元素,如果找不到元素,则返回null:

提供与上面相同的异常提供与上面相同的异常您可以显示Linq表达式的其余部分吗
return customers.FirstOrDefault();