实体框架4 Single()vs First()vs FirstOrDefault() [英] Entity Framework 4 Single() vs First() vs FirstOrDefault()

查看:77
本文介绍了实体框架4 Single()vs First()vs FirstOrDefault()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



有人有任何人有一个链接比较所有这些,或一个快速的解释,为什么你会使用一个在另一个?还有更多的运营商,我不知道吗?



谢谢。

解决方案>

以下是不同方法的概述:




  • Find() - 当您想要获取项目时首要的关键。如果找不到某项,则返回null。在进入数据库之前,它会在上下文中查看(如Yaron在评论中指出的),如果您需要在同一个上下文生存时多次获取相同的实体,那么这可能是一个重要的效率因素。

    / li>
  • Single() - 当您希望一个查询返回一个项目时。如果查询没有返回一个项目,这将抛出异常。


  • SingleOrDefault() - 当您希望通过查询返回零个或一个项目(即您不确定是否存在具有给定键的项目)。如果查询不返回零或一个项目,这将抛出异常。


  • First() - 当您期望一个或多个项目由查询,但您只想访问代码中的第一个项目(排序可能在这里的查询中很重要)。如果查询不返回至少一个项目,这将抛出异常。


  • FirstOrDefault() - 当您希望返回一个或多个项目时查询,但您只想访问代码中的第一个项目(即您不确定是否存在具有给定键的项目)



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.

解决方案

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)

这篇关于实体框架4 Single()vs First()vs FirstOrDefault()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆