当我通过一个带有以下代码的预言切换时,它成功抓住了第一个出现的例外,并在我的错误列表中添加了代号。在循环的所有后续迭代中,它将继续捕捉上一个例外。
我怎样才能适当抓住例外,撤销或清除失败的删除请求,以便随后执行删除。
public ActionResult Delete(int[] ListData)
{
List<int> removed = new List<int>();
List<int> error = new List<int>();
Item deleteMe;
foreach (var id in ListData)
{
deleteMe = this.getValidObject(id);
if (deleteMe == null)
{
error.Add(id);
continue;
}
try
{
this.DB.Items.DeleteObject(deleteMe);
this.DB.SaveChanges();
removed.Add(id);
}
catch (DataException ex)
{
// revert change to this.DB.Items?
error.Add(id);
}
}
if (error.Count > 0)
{
return Json(new { Success = false, Removed = removed, Error = error });
}
return Json(new { Success = true, Removed = removed });
}
我搜索了 SO 和 Google, 大多数人会先处理所有的删除对象, 然后保存更改, 这样它就是一个交易。 但我需要它单独处理每笔交易, 这样单项失败不会阻止其余的交易 。
我在使用实体框架4。
我得到的例外是这个具体例子,因为外国钥匙与正在删除的项目相关联。 在制作过程中,我将处理这种情形,但它应该能够继续,不管例外是什么。