实体框架中的OptimisticConcurrencyException [英] OptimisticConcurrencyException in Entity Framework

查看:386
本文介绍了实体框架中的OptimisticConcurrencyException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景:
我在db中有一些表ProductCategory的记录.
在一个窗口中,我已经加载了记录,并且可以通过导航按钮轻松地进行操作. (第一,下一个,上一个,最后一个)
我已经在此表单上加载了一条记录,说ID = 5.
现在,我回到db并删除该记录.
我仍然可以在表单上看到ID = 5.
现在,当我尝试更新此记录时,出现了OptimisticConcurrencyException.
当客户端上有一条记录已被其他人删除时,我该如何在我的应用程序中处理此类Scenerio.

谢谢!

Scenario:
I have some records in db for a table ProductCategory.
On one window form i have loaded the records and easily can c through navigation button. (First, Next, Previous, Last)
I have loaded a record say ID=5 on this form.
Now i go back to db and delete that record.
I can still seeing ID=5 on my form.
Now when i am trying to update this record i got OptimisticConcurrencyException.
How can i handle such scenerio in my application when there is a record on client side which has already deleted by some one else.

Thanks!

推荐答案

典型的解决方案是使用已知的主键重新获取.根据获取,您将获得新行(如果已更新),或者获得有关该行已不存在的信息.您可以在处理异常的地方进行重新获取.
Typical solution for this is a re-fetch using the known primary key. Based on the fetch you''ll either get the new row (if it''s updated) or you get information that the row exists no more. You can do the re-fetch where you handle the exception.


您可以在更新查询中的Where子句中使用Exists关键字.这是MSDN文档.该示例显示了select,但是它也可以与update一起使用.它在更新之前检查是否存在.

http://msdn.microsoft.com/en-us/library/ms188336.aspx [ ^ ]

这里也有一些例子. http://www.sqlservercurry.com/2010/02/if-row-exists-update-else-insert-in-sql.html [
You can use the Exists keyword at the Where clause in your update query. Here is the MSDN documentation. The example shows select, but this can be used with update as well. It checks the existence before update.

http://msdn.microsoft.com/en-us/library/ms188336.aspx[^]

Some example here as well. http://www.sqlservercurry.com/2010/02/if-row-exists-update-else-insert-in-sql.html[^]

After updates as Mika said re fetch the results, so that you will get the updated set.


这篇关于实体框架中的OptimisticConcurrencyException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆