EF Core 在 SaveChangesAsync() 过程中遗漏了所做的更改。

huangapple go评论58阅读模式
英文:

EF Core misses changes made during SaveChangesAsync()

问题

I'm calling DbContext.SaveChangesAsync() to save my objects to the database. This takes about 120 ms.

If an event changes a tracked object's property during this time, this change is neither directly saved to the database nor tracked by the EF Core ChangeTracker to save it later.

That means, that if I call DbContext.SaveChangesAsync() later again, the new property value is still not saved to the database because the EF Core ChangeTracking doesn't see this change.

I was expecting that DbContext.SaveChangesAsync() can't save changes to the database that are made during the operation. But I was expecting that the EF Core ChangeTracker would track this change correctly to make it possible to later save it to the database.

英文:

I'm calling DbContext.SaveChangesAsync() to save my objects to the database. This takes about 120 ms.

If an event changes an tracked object's property during this time, this change is neither directly saved to database nor tracked by the EF Core ChangeTracker to save it later.

That means, that if I call DbContext.SaveChangesAsync() later again, the new property value is still not saved to the database because the EF Core ChangeTracking doesn't see this change.

I was expecting that DbContext.SaveChangesAsync() can't save changes to the database that are made during the operation. But I was expecting that the EF Core ChangeTracker would track this change correctly to make it possible to later save it to the database.

答案1

得分: 3

可能的解决方案之一是显式标记对象为 Modified。有一个 Entry() 方法用于获取要修改的对象的 EntityEntry,然后调用 EntityEntry.State 属性将其状态设置为 Modified

db.Entry(yourEntity).State = EntityState.Modified;

注意:有关更多详细信息,可以参考问题文档

多个 DbContext 实例也可以用于在需要时切换,因为 EF Core 实现了乐观并发,不过在我看来,如果没有深刻的理解,这可能会引发更多问题而不是好处。因此,每个人在使用时都应小心谨慎,因为它可能导致意外行为和问题。

英文:

One of possible solutions is to mark the object as Modified explicitly. There is an Entry() method to obtain an EntityEntry for the object you want to modify, and then calling the EntityEntry.State property to set its state to Modified:

db.Entry(yourEntity).State = EntityState.Modified;

Note: some more details can be found by the question and documentation.

Multiple DbContext instances might also be used to switch between them for such cases as EF Core implements optimistic concurrency, however IMO it might cause more problems than benefits without deep understanding. So everyone should use it carefully as it can lead to unexpected behaviour and issues.

huangapple
  • 本文由 发表于 2023年2月27日 03:41:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75574584.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定