.net 实体框架 4 Single() vs First() vs FirstOrDefault()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3485317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Entity Framework 4 Single() vs First() vs FirstOrDefault()
提问by asfsadf
I'm having a devil of a time finding a comparison of the different ways to query for a single item, and when to use each.
我有一段时间很难找到查询单个项目的不同方法的比较,以及何时使用每种方法。
Does anyone have a link that compares all these, or a quick explanation as to why you would use one over the other? Are there still more operators that I am unaware of?
有没有人有比较所有这些的链接,或者关于为什么你会使用一个而不是另一个的快速解释?还有更多我不知道的运营商吗?
Thank you.
谢谢你。
回答by Steve Willcock
Here is an overview of the different methods:
以下是不同方法的概述:
Find() - when you want to get an item by primary key. This will return null if it can't find an item. It will look in the context before going to the database (as pointed out by Yaron in the comments) which can be an important efficiency factor if you need to get the same entity multiple times while the same context is alive.
Single() - when you expect exactly one item to be returned by a query. This will throw an exception if the query does not return exactly one item.
SingleOrDefault() - when you expect zero or one items to be returned by a query (i.e. you are not sure if an item with a given key exists). This will throw an exception if the query does not return zero or one items.
First() - when you expect one or more items to be returned by a query but you only want to access the first item in your code (ordering could be important in the query here). This will throw an exception if the query does not return at least one item.
FirstOrDefault() - when you expect zero or more items to be returned by a query but you only want to access the first item in your code (i.e. you are not sure if an item with a given key exists)
Find() - 当您想通过主键获取项目时。如果找不到项目,这将返回 null。它将在进入数据库之前查看上下文(正如 Yaron 在评论中指出的那样),如果您需要在相同上下文处于活动状态时多次获取相同实体,这可能是一个重要的效率因素。
Single() - 当您期望查询只返回一项时。如果查询没有准确返回一项,这将引发异常。
SingleOrDefault() - 当您希望查询返回零个或一个项目时(即您不确定具有给定键的项目是否存在)。如果查询未返回零或一项,这将引发异常。
First() - 当您希望查询返回一个或多个项目,但您只想访问代码中的第一个项目(在此处的查询中排序可能很重要)。如果查询未返回至少一项,这将引发异常。
FirstOrDefault() - 当您希望查询返回零个或多个项目,但您只想访问代码中的第一个项目(即您不确定是否存在具有给定键的项目)
回答by zeeshanhirani
I always tend to use FirstOrDefault. If you really want to be picky with performance then you should use FirstOrDefaultin EF. Under the covers SingleOrDefaultuses top (2) in the query because, it needs to check if there is a second row that matches the criteria and if it does, it throws an exception. Basically in SingleOrDefaultyou are saying that you want to throw an exception if your query returns more then 1 record.
我总是倾向于使用FirstOrDefault. 如果你真的想对性能挑剔,那么你应该FirstOrDefault在 EF 中使用。在后台SingleOrDefault在查询中使用 top (2) 是因为,它需要检查是否有第二行符合条件,如果有,则抛出异常。基本上SingleOrDefault你是说如果你的查询返回超过 1 条记录,你想抛出一个异常。
回答by Steven
It's really very simple: Singlereturns a single item and throw an exception if there is either none or more than one item. Firstwill return the first item or throw when there is no item. FirstOrDefaultwill return the first item or return the default value (which is nullin case the given type is a reference type) when there is no item.
这真的很简单:Single返回单个项目并在没有或多个项目时抛出异常。First将返回第一个项目或在没有项目时抛出。当没有项目时,FirstOrDefault将返回第一项或返回默认值(null如果给定类型是引用类型)。
This is the behavior the API is supposed to have. Note however that the underlying implementation could have a different behavior. While Entity Framework obeys this, a O/RM like LLBLGen can also return nullwhen calling Firstwhich is a very strange thing. This was a very strange (and stubborn) decision by the designer IMO.
这是 API 应该具有的行为。但是请注意,底层实现可能具有不同的行为。虽然实体框架遵守这一点,但像 LLBLGen 这样的 O/RM 也可以null在调用时返回,First这是一件非常奇怪的事情。这是设计师 IMO 的一个非常奇怪(而且顽固)的决定。
回答by Chris Shaffer
The four methods each have their place; Though you really only have two different operations.
这四种方法各有千秋;虽然你真的只有两种不同的操作。
- First - Expecting a result set that contains multiple items, give me the first item in that set.
- Single - Expecting a single result back, give me that item.
- 第一 - 期望包含多个项目的结果集,给我该集中的第一个项目。
- 单 - 期待一个单一的结果,给我那个项目。
The xxxxOrDefault() version just adds on "I don't want to consider an empty result set to be an exceptional circumstance."
xxxxOrDefault() 版本只是添加了“我不想将空结果集视为特殊情况”。
回答by Kryszal
On the other side, you can divide these methods by the core logic, like this:
另一方面,您可以通过核心逻辑来划分这些方法,如下所示:
- Method will query database directly: Single(), SingleOrDefault(), First(), FirstOrDefault()
- Method will perform a search in cache before even issuing the query against the database: Find()
- 方法将直接查询数据库:Single()、SingleOrDefault()、First()、FirstOrDefault()
- 在对数据库发出查询之前,方法将在缓存中执行搜索:Find()
For some performance details, especially in the second case you can look here: https://msdn.microsoft.com/en-us/data/hh949853.aspx?f=255&MSPPError=-2147217396#3
有关一些性能细节,尤其是在第二种情况下,您可以在这里查看:https: //msdn.microsoft.com/en-us/data/hh949853.aspx?f=255&MSPPError=-2147217396#3
In addition, in the first group you can define complex queries, but with Find()method you can provide only entity key for search.
此外,在第一组中,您可以定义复杂的查询,但使用Find()方法,您只能提供用于搜索的实体键。
回答by MilkTea027
Single()and SingleOrDefault()is usually used on unique identifiers such as IDs, while First()or FirstOrDefault()is usually used for a query that could have multiple result but you want only the "Top 1".
Single()和SingleOrDefault()通常用于唯一标识符,例如 ID,而First()或FirstOrDefault()通常用于可能有多个结果但您只需要"Top 1" 的查询。
Single()or First()would throw an exception if no result is returned, SingleOrDefault()and FirstOrDefault()catches the exception and returns null or default(ResultDataType).
如果没有返回结果,Single()或First()将抛出异常,SingleOrDefault()和FirstOrDefault()捕获异常并返回 null 或 default(ResultDataType)。

