使用 EntityFramework Core 我有这段代码:
var theStudent = new Student();
theStudent.Title = "Mehran"
theStudent.Status = 1
mainDbContext.Set<Student>().Add(theStudent);
await mainDbContext.SaveChangesAsync();
// In reality data is changed by another program. To simulate it here I alter the data by another dbcontext and raw SQL
using (var utilDbContext = new MelkRadarDbContext())
{
var command = " update dbo.Student set status=2 where Id=@p0";
utilDbContext.Database.ExecuteSqlCommand(command, theStudent.Id);
}
var reloadedStudent = await mainDbContext.Set<Student>()
.Where(s => s.Id == theStudent.Id)
.FirstOrDefaultAsync();
Assert.AreNotEqual(reloadedStudent, student);
Assert.AreEqual(reloadedStudent.Status, 2);
两个断言都失败了。似乎在第二次调用时,mainDbContext
仍然返回旧的 theStudent
对象作为 reloadedStudent
,并且没有从数据库中加载它来获取新鲜的数据。为什么会这样?我应该如何获取数据库中的新数据?
最佳答案
简答:
你有两个选择:
[不推荐] 使用
Reload
或ReloadAsync
每个实体的方法:await mainDbContext.Entry(theStudent).ReloadAsync();
由于必须分别为每个实体调用它,因此当您需要重新加载一堆实体时效率非常低。
[推荐] 创建一个新的
DbContext
.这是解决陈旧数据问题的 final方法。
详情:
DbContext
s 的设计生命周期很短。他们实现了 Unit Of Work模式,因此建议创建一个 DbContext
对于每批相关操作(业务交易)——例如用户操作(按下“保存”按钮)。虽然有一个单一的常见做法 DbContext
对于每个 HTTP 请求(在 Web 应用程序或 Web 服务的上下文中)都满足此要求,但有时您需要在请求中执行多个“操作批处理”。那是您需要考虑创建更多 DbContext
的时候了
整点守单DbContext
对于一系列操作,就是缓存、跟踪和延迟加载。每当您需要重新加载数据时,很明显您不再需要从那个地方开始的那些功能。所以使用新的 DbContext
是有意义的.
一个很好回答的问题是,为什么您首先需要新数据?如果您需要根据数据做出关键决策,并且依赖陈旧数据会导致数据存储不一致,那么即使刷新实体也无济于事。在这种情况下,您需要使用更强大的机制,例如锁(数据库或其他)来防止数据过时。
注意:在 Entity Framework 6 中有一个 Refresh
可用于一次刷新所有对象的方法。此方法在 Entity Framework Core 中不可用,因为它 din't prove to be all that useful .
关于c# - Entity Framework Core 不返回刷新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51315425/