使用 Find()
和 Single()
从上下文查询数据时有什么不同。
两者都返回被请求的实体。
我在 Microsoft 上找到的一些示例使用 Single
、SingleOrDefault
变体来查询实体。有些使用Find
方法。
使用其中一种时是否有任何“性能”优势?
最佳答案
虽然它们看起来一样,但在一些基本方面却非常不同
简而言之,Find
从上下文的本地缓存中搜索开始。如果未找到匹配项,则它会向数据库发送查询。
文档是您的 friend
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.
更一般
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/