英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论