在ADO.NET实体框架乐观并发实体、框架、乐观、ADO

2023-09-03 16:20:44 作者:冰是睡着的水﹏

我发现的MSDN文章描述EF如何处理并发保存更改时:

  

在默认情况下[...]对象服务对象节省   对数据库的修改无   检查并发。对于   这可能会遇到一个特性   并发程度高,我们   建议实体属性是   在概念层定义   的一个属性   ConcurrencyMode =固定

我有两个问题:

有在我的模型没有属性,其中 ConcurrencyMode =固定,它是安全的,我的假设,如果曾经的 OptimisticConcurrencyException 保存更改的时候,那是因为实体不再在数据存储中存在,也就是说,它已被删除其他用户,还是我失去了一些东西?被抛出

我想EF执行一个更新语句来,看起来是这样的,其中,因为我看到它,只会导致 OptimisticConcurrencyException 被抛出,如果有ID的人= 1不存在:

 更新人所设定的名字='约翰'和姓氏='史密斯'WHERE ID = 1
 

在使用 ConcurrencyMode =固定,不会删除实体时以及EF检查并发?换句话说,将EF永远执行删除语句来,看起来像这样(的不仅仅是在,其中 -clause):

  DELETE FROM人WHERE ID = 1和姓氏='李四'
 
EF框架的优点是什么

解决方案

好问题。

(1)是的,但不幸的是它并不是如此简单。由于EF(3.5)具有独立的关联模型,该协会是独​​立处理过了,即使你还没有说的那么它将成为并发检查的一部分,在更新和删除。

即。当您更新一个人,你会经常看到像这样的更新:

 更新人所设定的合作伙伴= NULL和名字='约翰'和姓氏=史密斯
WHERE ID = 1和合作伙伴= 2
 

即。伙伴是FK列。

这在4.0的所有变化,如果你使用的FK关联,因为我们预计大多数人了。

(2)删除任何ConcurrencyMode =固定属性中删除检查。当你有一个存储过程进行删除不接受并发值的除外。

希望这有助于

亚历

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:

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

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'

解决方案

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