Concurrency exceptions in Entity Framework

拟墨画扇 提交于 2019-12-03 20:43:05

问题


When calling SaveChanges / SaveChangesAsync in Entity Framework (CF, C#), if a change conflict occurs (for example, the values has been updated since last read thingy), then which of these two exceptions DbUpdateConcurrencyException OR OptimisticConcurrencyException shall I catch?

And what is the difference between them?


回答1:


DbUpdateConcurrencyException is a specific exception thrown by DbContext, so this is the one to catch. This exception may be caused by an underlying OptimisticConcurrencyException, but if so, this exception is wrapped as the inner exception.

Not all update exceptions are caused by concurrency, so you also have to catch DbUpdateException after catching DbUpdateConcurrencyException (because the latter is a subtype of DbUpdateException).

See also Entity framework 5.0 handle optimistic concurrency exception?.




回答2:


You will get an OptimisticConcurrencyException. Have a look at this.

Now coming to the diffrence.

  • OptimisticConcurrencyException:thrown when an optimistic concurrency violation occurs(suppose more than one perople are changing to the same result,and this will cause the problem of not being sychronized)
  • DbUpdateConcurrencyException:Exception thrown by DbContext when the expected behavior is that SaveChanges for an entity would result in a database update but in fact no rows in the database were affected. This shows that the database has been concurrently updated and a concurrency token that was expected to match did not actually match. State entries referenced by this exception are not serialized due to security and access to the state entries after serialization will return null.


来源:https://stackoverflow.com/questions/22035630/concurrency-exceptions-in-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!