删除实体时如何忽略DbUpdateConcurrencyException [英] How to ignore a DbUpdateConcurrencyException when deleting an entity

查看:111
本文介绍了删除实体时如何忽略DbUpdateConcurrencyException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,可以将大量数据读取到内存中并进行批量处理。

I have an app that reads a lot of data into memory and processes it in a batches.

我想要的是让实体框架在删除已删除的实体时忽略 DbUpdateConcurrencyException

What I want is for entity framework to ignore DbUpdateConcurrencyException when deleting an entity that has already been deleted.

原因是,到实体被处理并标记为删除时,它可能已经从数据库中删除。

The reason is that by the time an entity has been processed and marked for deletion, it may already have been deleted from the DB.

显然删除已删除的行不是问题,也不应该引起错误,我只需要一种方法告诉实体框架:)

Obliviously deleting a row that has already been deleted isn't a problem and shouldn't cause an error, I just need a way to tell entity framework that :)

示例

Db.Entry(itemToRemove).State = EntityState.Deleted;
Db.SaveChanges();

如果 itemToRemove 已经存在,则会导致错误

Causes an error if itemToRemove has already been deleted.

注意: Db.Configuration.ValidateOnSaveEnabled = false; 不能解决此问题,因为建议使用另一个线程。

Note: Db.Configuration.ValidateOnSaveEnabled = false; doesn't fix this as another thread suggested.

推荐答案

如何?

Db.Entry(itemToRemove).State = EntityState.Deleted;

bool saveFailed;
do
{
    saveFailed = false;
    try
    {
       Db.SaveChanges();
    }
    catch(DbUpdateConcurrencyException ex)
    {
       saveFailed = true;
       var entry = ex.Entries.Single();
       //The MSDN examples use Single so I think there will be only one
       //but if you prefer - do it for all entries
       //foreach(var entry in ex.Entries)
       //{
       if(entry.State == EntityState.Deleted)
          //When EF deletes an item its state is set to Detached
          //http://msdn.microsoft.com/en-us/data/jj592676.aspx
          entry.State = EntityState.Detached;
       else
          entry.OriginalValues.SetValues(entry.GetDatabaseValues());
          //throw; //You may prefer not to resolve when updating
       //}
    }
} while (saveFailed);

此处更多:
解决开放式并发异常

这篇关于删除实体时如何忽略DbUpdateConcurrencyException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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