Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DbUpdateException on SaveChanges keeps throwing

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.

like image 781
Francois Stock Avatar asked Sep 12 '26 16:09

Francois Stock


1 Answers

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.

like image 169
Augusto Barreto Avatar answered Sep 15 '26 05:09

Augusto Barreto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!