SaveChanges 上的 DbUpdateException 不断抛出

DbUpdateException on SaveChanges keeps throwing

我在使用 Entity Framework 6.0 数据库优先访问数据开发 Asp.Net Mvc 5 时遇到奇怪的异常。

首先,当我尝试删除记录时,SaveChanges 抛出 DbUpdateException:

The DELETE statement conflicted with the REFERENCE constraint "ForeignKeyName". 
(...)
The statement has been terminated.

这个异常随后被我们的 ExceptionFilter 捕获:

public void OnException(ExceptionContext filterContext)
{
    // Opening popup
    filterContext.ExceptionHandled = true;
}

到目前为止,一切都很好。但是,如果在此之后再次调用 SaveChanges 方法来更新另一个实体,则会继续抛出相同的异常。

我教过它与调试模式有关 (cf post Exception seems to be thrown repeatedly when debugging) 但我在发布时遇到了同样的问题。

如有任何帮助,我们将不胜感激。

您可能在抛出删除异常后重复使用同一个 DbContext 实例。如果 SaveChanges() 失败,更改仍由 DbContext.ChangeTracker 跟踪。您必须创建一个新的 DbContext 实例或清除更改跟踪器。