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

查看:24
本文介绍了实体框架 4 Single() vs First() vs 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?

谢谢.

推荐答案

以下是不同方法的概述:

Here is an overview of the different methods:

  • Find() - 当您想通过主键获取项目时.如果找不到项目,这将返回 null.它将在进入数据库之前查看上下文(正如 Yaron 在评论中指出的那样),如果您需要在相同上下文处于活动状态时多次获取相同实体,这可能是一个重要的效率因素.

  • 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() - 当您期望查询只返回一项时.如果查询没有准确返回一项,这将引发异常.

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() - 当您希望查询返回零个或一个项目时(即您不确定具有给定键的项目是否存在).如果查询未返回零或一项,这将引发异常.

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() - 当您希望查询返回一个或多个项目,但您只想访问代码中的第一个项目(此处的查询中排序可能很重要).如果查询未返回至少一项,这将引发异常.

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() - 当您希望查询返回零个或多个项目,但您只想访问代码中的第一个项目(即您不确定是否存在具有给定键的项目)

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天全站免登陆