Handling exceptions for each entity in context.saveChanges()

ado.net c# entity-framework-6 exception


Is it possible to get the specific exception of failed save for each entity in a bundle?

The simple use of saveChanges() gives one exception for all the bandle .

This is my code with try-catch block.:

  foreach (EntityBase ent in response.Entities)
                    //save each ent ?
                catch (DbEntityValidationException ex){...}
                catch (DbUpdateException e) { ...}

                catch (Exception ex){...}
7/14/2018 4:46:30 PM

Accepted Answer

This is one option to control entity in saveChanges()

foreach (AbstractEntity ent in response.Entities)
                    //defining new Entry for context - action by state
                    ctx.Entry(ent).State = ent.getEntityState();
                    ctx.Entry(ent).State = EntityState.Detached;

                catch (Exception ex){
string errorMessages = ex.InnerException.InnerException.ToString();
                throw ex.InnerException.InnerException;}
7/12/2018 6:32:03 AM

Popular Answer

Not without calling save changes after every change you make to an attached/tracked entity.

I would advise against that as it could slow down your application depending on how many changes you want to commit. If you do decide to do this and you want to roll back previous changes if there is a failure you will need to add a wrapped transaction you commit/rollback after you run through the entire set of changes. You will also have to manually detach/revert changes after a failure so that the next save changes on the next change does not trigger the previous failure that just occurred. The easiest way to do the latter might be to detach that entity or recreate the DbContext instance.

If you wanted to validate before the save to the DbContext then see this previous question and answer. It can't catch all errors like constraints on unique indexes but it can catch anything where constraints on the data are violated like missing required values: Validating entities before saving and removing from context

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow