我知道其他人已经写了为什么你使用其中一个,但我想我应该说明为什么你不应该使用一个,当你使用另一个.
Note: In my code, I will typically use 100 and 101 but that's a different question.
例如,一个使用复合键(ID
Lang
)以不同语言存储Customers
的表:
DBContext db = new DBContext();
Customer customer = db.Customers.Where( c=> c.ID == 5 ).First();
上面的代码引入了一个可能的逻辑错误(难以跟踪).它将返回多个记录(假设您有多个语言的客户记录),但它总是只返回第一个记录...这有时可能有用...但其他人则不然.这是不可预测的.
由于您意图是返回单个Customer
,因此使用Single()
;
下面将抛出一个异常(在本例中,这是您想要的):
DBContext db = new DBContext();
Customer customer = db.Customers.Where( c=> c.ID == 5 ).Single();
然后,你简单地打自己的额头,然后对自己说…哎呀!我忘了语言领域了!以下是正确的版本:
DBContext db = new DBContext();
Customer customer = db.Customers.Where( c=> c.ID == 5 && c.Lang == "en" ).Single();
First()
在以下情况下很有用:
DBContext db = new DBContext();
NewsItem newsitem = db.NewsItems.OrderByDescending( n => n.AddedDate ).First();
它将返回一个对象,因为您正在使用排序,所以它将是返回的最新记录.
当您觉得Single()
应该显式地始终返回1条记录时,使用Single()
将帮助您避免逻辑错误.