Handling exceptions for each entity in context.saveChanges()

ado.net c# entity-framework-6 exception

Question

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)
            {
                try
                {
                    //save each ent ?
                }
                catch (DbEntityValidationException ex){...}
                catch (DbUpdateException e) { ...}

                catch (Exception ex){...}
            }
1
-1
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.SaveChanges();
                    ctx.Entry(ent).State = EntityState.Detached;
                } 


                catch (Exception ex){
string errorMessages = ex.InnerException.InnerException.ToString();
                throw ex.InnerException.InnerException;}
            }
0
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





Related

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