c# - .Find 方法能否在多用户环境中返回错误结果

标签 c# entity-framework

在此 MSDN 链接中提到了以下有关 .Find() 方法的内容

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.

但这会导致问题吗?假设一个对象被标记为已添加状态,但在将其保存到数据库之前发生了异常。所以 find 可能会返回具有 Added 状态的对象,该对象稍后尚未保存到数据库中。

第二个问题,如果 .Find 在上下文中找到一个对象,并且该对象在找到它后立即在数据库中更新,那么上下文中的对象版本将是旧的怎么办?

那么,使用 .Find() 而不是使用 .Where.firstordefault 基于主键进行搜索,我可以获得哪些好处(a=>a.primarykey ==id)?

最佳答案

好吧,文档说明 Find...

Uses the primary key value to attempt to find an entity tracked by the context. If the entity is not in the context then a query will be executed and evaluated against the data in the data source,

所以它首先搜索缓存。如果缓存中的内容是旧的(或者数据库中不存在 - 并且可能永远不会)那么这就是你得到的。如果在缓存中找不到实体,它只会进行查询。我不会说它返回“错误”的东西,因为它被定义为做什么。如果您需要查找可能被其他用户更改或保证存在于数据库中的数据,您将需要坚持使用查询。

关于c# - .Find 方法能否在多用户环境中返回错误结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18220058/

相关文章:

c# - 为什么我的 WPF 应用程序会在我碰撞鼠标滚轮时崩溃?

c# - 为什么 Awaiters (async/await) 是结构体而不是类?可以使用类吗?

c# - Lambda 表达式不正确

c# - 没有返回记录时的 EF Linq 产品总和

.net - 在 Entity Framework 中建模订单与产品的关系

java - spring-data-mongodb 实体实现接口(interface)创建错误的集合

c# - 如何使用 dataGridView C# 中的行更新数据库中的行

c# - 如何使用 C# 创建新的 SQL Server 2008 R2 登录

sql - 延迟加载真的很糟糕吗?

entity-framework - SQLite 与 Entity Framework