Optimistic concurrency in ADO.NET Entity Framework

纵然是瞬间 提交于 2019-12-22 04:51:10

问题


I found an MSDN article that describes how EF handles concurrency when saving changes:

By default [...] Object Services saves object changes to the database without checking for concurrency. For properties that might experience a high degree of concurrency, we recommend that the entity property be defined in the conceptual layer with an attribute of ConcurrencyMode="fixed"

I have two questions:

  1. Having no properties in my model where ConcurrencyMode="fixed", is it safe for me to assume that if ever an OptimisticConcurrencyException is thrown when saving changes, it is because the entity no longer exists in the data store, i.e. it has been deleted by another user, or am I missing something?

    I imagine EF executing an UPDATE-statement that looks something like this, which, as I see it, will only cause an OptimisticConcurrencyException to be thrown if the Person with ID = 1 doesn't exist:

    UPDATE Person SET FirstName = 'John' AND LastName = 'Smith' WHERE ID = 1
    
  2. When using ConcurrencyMode="fixed", does EF check for concurrency when deleting entities as well? In other words, will EF ever execute a DELETE-statement that looks like this (with more than just the primary key in the WHERE-clause):

    DELETE FROM Person WHERE ID = 1 AND LastName = 'Doe'
    

回答1:


Good question.

(1) Yes, but unfortunately it is not quite this simple. Because the EF (3.5) has an independent association model, the association is treated independently too, and even though you haven't said so it becomes part of the concurrency checks during UPDATES and DELETES.

i.e. when you update a Person you will often see updates that look like this:

UPDATE Person SET Partner = NULL AND FirstName = 'John' AND LastName = 'Smith' 
WHERE ID = 1 AND Partner = 2

i.e. Partner is an FK column.

This all changes in 4.0 if you use FK associations, as we expect most people too.

(2) For DELETE any ConcurrencyMode = 'fixed' properties ARE checked during delete. The exception is when you have a SPROC for delete that doesn't accept that Concurrency values.

Hope this helps

Alex



来源:https://stackoverflow.com/questions/1221975/optimistic-concurrency-in-ado-net-entity-framework

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