3

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.

Community
  • 1
  • 1
Francois Stock
  • 685
  • 1
  • 9
  • 17

1 Answers1

2

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.

Augusto Barreto
  • 3,637
  • 4
  • 29
  • 39
  • 1
    Or Rollback the changes made to your context –  Feb 02 '15 at 21:33
  • 1
    I've chosen the 2d option and wrote a rollback method (cf. [Undo changes in entity framework entities](http://stackoverflow.com/questions/5466677/undo-changes-in-entity-framework-entities)). Thanks, I didn't realize I would have to clear entity after handling the exception. – Francois Stock Feb 03 '15 at 09:28