C# LINQ to SQL:如果数据库不返回值,Count()将引发异常
我有一个linq to sql语句,它将一组客户详细信息返回给客户对象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
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();