ADO.NET 实体框架中的乐观并发
我发现一篇 MSDN 文章 描述了保存更改时 EF 如何处理并发:
默认情况下[...]对象服务保存对象 对数据库的更改没有 检查并发性。 为了 可能会经历 高并发,我们 建议实体属性为 在概念层中定义为 的一个属性 ConcurrencyMode="固定"
我有两个问题:
我的模型中没有
ConcurrencyMode="fixed"
的属性,我可以安全地假设如果出现OptimisticConcurrencyException
code> 保存更改时抛出,这是因为该实体不再存在于数据存储中,即它已被其他用户删除,或者我丢失了某些内容?我想象 EF 执行一个看起来像这样的
UPDATE
语句,据我所知,如果 Person 具有ID = 1 不存在:UPDATE Person SET FirstName = 'John' AND LastName = 'Smith' WHERE ID = 1
使用
ConcurrencyMode="fixed"
时,EF 在删除实体时是否也会检查并发性? 换句话说,EF 是否会执行如下所示的DELETE
语句(不仅仅是WHERE
子句中的主键):从 ID = 1 AND LastName = 'Doe' 的人员中删除
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 anOptimisticConcurrencyException
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 anOptimisticConcurrencyException
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 aDELETE
-statement that looks like this (with more than just the primary key in theWHERE
-clause):DELETE FROM Person WHERE ID = 1 AND LastName = 'Doe'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好问题。
(1) 是的,但不幸的是事情没有这么简单。 因为 EF (3.5) 具有独立的关联模型,所以关联也被独立处理,即使您没有这么说,它也会成为 UPDATES 和 DELETES 期间并发检查的一部分。
即,当您更新人员时,您经常会看到如下所示的更新:
即“合作伙伴”是一个 FK 列。
如果您使用 FK 关联,这一切都会在 4.0 中发生变化,正如我们大多数人所期望的那样。
(2) 对于 DELETE,在删除期间会检查任何 ConcurrencyMode = 'fixed' 属性。 例外情况是当您有一个用于删除的 SPROC 不接受该并发值时。
希望这对
亚历克斯有帮助
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:
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