Entity Framework has internal capabilities to validate data against the EF model, but there may be a situation when you have some restrictions on the database level. For example, you are importing a large amount of data on a table-per-table basis, and suddenly some rows are breaking the foreign key constraints. In this case database throws an error, sends it to EF, and EF returns DbUpdateException to your code. What’s next?
1) You can examine the entity which caused the exception. DbUpdateException has a property Entries that holds failed entities.
2) If you want to ignore this entity (maybe it’s an expected situation where some data could break foreign key and that rows should be skipped), you need to change the state of DbEntityEntry to Detached. This will remove the entity from context. So it’ll never be saved later.
3) After these steps you must repeat SaveChanges().
The following code snippet is an example of how you can implement the above mentioned logic.
bool isSaved = false;
// save data
//set flag to exit loop
isSaved = true;
catch (System.Data.Entity.Infrastructure.DbUpdateException ex)
// get failed entries
var entries = ex.Entries;
foreach (var entry in entries)
// change state to remove it from context
entry.State = System.Data.Entity.EntityState.Detached;
catch (Exception ex)
// quit if a severe error occurred