I encounter weird exceptions while developping Asp.Net Mvc 5 using Entity Framework 6.0 database-first to access data.
First, when I try to delete a record, a DbUpdateException is thrown on SaveChanges :
The DELETE statement conflicted with the REFERENCE constraint "ForeignKeyName".
(...)
The statement has been terminated.
This exception is then caught by our ExceptionFilter :
public void OnException(ExceptionContext filterContext)
{
// Opening popup
filterContext.ExceptionHandled = true;
}
Up to now, everything is fine. However, if after that the SavesChanges method is called again to update another entity, the same exception keeps throwing.
I taught it was related to the debug mode (cf post Exception seems to be thrown repeatedly when debugging) but I've the same issue in release.
Any help would be appreciated.
You are probably reusing the same DbContext instance after the delete exception is thrown. If SaveChanges() fails, the changes are still being tracked by the DbContext.ChangeTracker. You have to create a new DbContext instance or clear the change tracker.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With