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

查看:19
本文介绍了删除实体时如何忽略 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天全站免登陆