c# - DbContext.Find() 和 DbContext.SingleOrDefault() Entity Framework Core 之间的区别

标签 c# entity-framework entity-framework-core

使用 Find()Single() 从上下文查询数据时有什么不同。 两者都返回被请求的实体。

我在 Microsoft 上找到的一些示例使用 SingleSingleOrDefault 变体来查询实体。有些使用Find方法。

使用其中一种时是否有任何“性能”优势?

最佳答案

虽然它们看起来一样,但在一些基本方面却非常不同

简而言之,Find 从上下文的本地缓存中搜索开始。如果未找到匹配项,则它会向数据库发送查询。

文档是您的 friend

DbSet.Find Method

Finds an entity with the given primary key values. If an entity with the given primary key values exists in the context, then it is returned immediately without making a request to the store. Otherwise, a request is made to the store for an entity with the given primary key values and this entity, if found, is attached to the context and returned. If no entity is found in the context or the store, then null is returned.

Queryable.SingleOrDefault Method

Returns a single, specific element of a sequence, or a default value if no such element is found.

Queryable.FirstOrDefault Method

Returns the first element of a sequence, or a default value if no element is found.

更一般

Querying and Finding Entities

The Find method on DbSet uses the primary key value to attempt to find an entity tracked by the context. If the entity is not found in the context then a query will be sent to the database to find the entity there. Null is returned if the entity is not found in the context or in the database.

Find is different from using a query in two significant ways:

  • A round-trip to the database will only be made if the entity with the given key is not found in the context.
  • Find will return entities that are in the Added state. That is, Find will return entities that have been added to the context but have not yet been saved to the database.

更新

Does this mean that if the entitiy was already being tracked (through lazy loading), then Find would actually have a better performance advantange when trying to querying again?

是的,它会有更好的性能

关于c# - DbContext.Find() 和 DbContext.SingleOrDefault() Entity Framework Core 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53078561/

相关文章:

entity-framework - 如何将子实体映射到父实体而不在子实体中引入原始类型父链接器?

c# - EF Core 中的 modelBuilder.Configurations.AddFromAssembly

c# - Entity Framework 核心。如何正确更新相关数据?

c# - 什么 C# 正则表达式可用于去除字符串中的点 (.)?

c# - 如何安装特定版本的nuget?

c# - 有什么方法可以在 WPF 中 block 复制部分图片?

asp.net - Entity Framework Core - 这可能表明 EF Core 中存在错误或限制

c# - 是否允许内联属性验证器?

c# - 未知的 CS1003 错误

c# - Entity Framework 代码首先初始化外键