正在查找和凡()。FirstOrDefault()相同呢?FirstOrDefault

2023-09-04 07:11:11 作者:笔尖微凉

我一直在使用查找(ID)扩展方法在实体框架5。但是,集合了许多我看到使用的例子在哪里(S => s.Id == 1),而我加入 FirstOrDefault()来获取对象,而不是一个集合。 这是一种风格的差异,或者是有功能性原因显而易见。凡()preference?

I have been using the Find(id) extension method with collections in Entity Framework 5. However, many of the examples I see use Where(s => s.Id == 1), to which I added FirstOrDefault() to get the object instead of a collection. Is this a style difference, or is there a functional reason for the apparent .Where() preference?

推荐答案

查找()有着根本的区别在哪里(),单(),第一()等,它会首先搜索对象在内存中,只打到数据库如果对象尚未加载。因此,尽量使用find()在可能的情况,因为它提供了加载速度可能受益于内存中。找到()只能与主键和不支持的lambda所以不是很灵活。

Find() has a fundamental difference to Where(), Single(), First() etc. in that it will first search for the object in memory and only hit the database if the object has not already been loaded. Thus try to use Find() where possible as it offers possible speed benefits of loading from memory. Find() only works with the primary key and doesn't support lambdas so it is not very flexible.

其中()通常用于获取对象的列表。为了找回我通常使用一个单独的对象可以是单()的SingleOrDefault(),第一(),FirstorDefault()。

Where() is typically used to get a listing of objects. To retrieve a single object I normally use either Single(), SingleorDefault(), First(), FirstorDefault().

单()和的SingleOrDefault()的不同,因为它们确保最多一个对象的能满足这有助于确保数据库中的数据的完整性的标准。他们单身的条款可以通过选择在SQL查询'TOP 2,然后如果这两个实体返回抛出异常。

Single() and SingleOrDefault() differ from First() and FirstOrDefault() as they ensure that a maximum of one object can satisfy the criteria which helps ensure the integrity of the data in the database. They 'Single' clauses do this by selecting 'TOP 2' in the SQL query and then throwing an exception if two entities are returned.

请注意,你不应该链这些给Where()子句的末尾。

Note that you should not chain these to the end of the Where() clause.

因此​​,而不是

.Where(s => s.Id == 1).FirstOrDefault();

使用:

.FirstOrDefault(s => s.Id == 1);

我写了一篇博客文章,充分探讨这个问题:http://judeokelly.com/primer-on-selecting-data-using-entity-framework/