.Single或Default with condition或Where子句

我有以下代码

return this.Storage.Customer.OfType() .Include(b => b.Order) .Where(cust => cust.Id == customerId && cust.CustomerType== (int)cusType) .SingleOrDefault(); 

它可以改写如下消除where。

  return this.Storage.Customer.OfType() .Include(b => b.Order) .SingleOrDefault(cust => cust.Id == customerId && cust.CustomerType == (int)cusType); 

哪一个更好实践,为什么?

首先,您需要了解其中的差异

 this.Storage.Customer.OfType() .Include(b => b.Order) .Where(cust => cust.Id == customerId && cust.CustomerType== (int)cusType) 

这只会创建一个查询但不会执行,直到你调用ToList方法。

SingleOrDefault方法实际上将执行查询。 因此,如果要在执行查询之前检查或执行某些操作,则应使用where,然后调用SingleOrDefault。

总的来说,根据我个人的意见,使用哪里是好的做法

由于调试函数返回值的复杂性以及在调试器中使用lambda表达式的不可能性,这是最好的方法:

 var temp = this.Storage.Customer.OfType() .Include(b => b.Order) .Where(cust => cust.Id == customerId && cust.CustomerType == (int)cusType); return temp.SingleOrDefault(); 

这样,如果SingleOrDefault()上存在exceptionSingleOrDefault()如果你正在执行复杂的表达式,这是很常见的),你可以在return上放置一个断点并在监视面板中执行: temp.ToList();

老post,这主要是基于意见的,但这是上面没有提到的另一个考虑因素:

SingleOrDefault子句不能跟其他术语如Select一样,因为正如Patel上面指出的那样,它实际上执行了查询。 例如,在您想要修改查询的路上说,只返回客户的名称:

 this.Storage.Customer.OfType() .Include(b => b.Order) .SingleOrDefault(cust => cust.Id == customerId && cust.CustomerType == (int)cusType) .Select(cust=>cust.Name); //compile error 

将无法工作,并且您无法将Select子句移动到SingleOrDefault之前,因为在SingleOrDefault ,对于lambda表达式, IdCustomerType字段将不可见。 相反,您需要先添加Where子句:

 this.Storage.Customer.OfType() .Include(b => b.Order) .Where(cust => cust.Id == customerId && cust.CustomerType == (int)cusType) .Select(cust=>cust.Name) .SingleOrDefault(); 

因此,因为Where子句通常是必要的并且始终至少具有良好的性能,所以总是将它用于一致性,可读性和可维护性可能是一种好习惯。