Finding the reason for DBUpdateException

.net c# entity-framework

Question

When calling DbContext.SaveChanges, I get a DbUpdateException:

An unhandled exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll. Additional information: An error occurred while updating the entries. See the inner exception for details.

Unfortunately, there is no inner exception (at least, not as far as I can see). Is there any way to see exactly why SaveChanges threw an exception? At the very least, it would be helpful to see what table SaveChanges tried to update with when the error occured.

1
43
2/27/2018 6:20:03 PM

Accepted Answer

When it seems that the real exception gets lost somewhere, your best bet is to break on every exception. Regardless of if it's catched or swallowed somewhere, in or out your reach, the debugger will break and allow you to see what's going on.

See this MSDN link for more info:

How to: Break When an Exception is Thrown

4
10/9/2015 4:48:18 PM

Popular Answer

This is my override of SaveChanges. It gives me a useful place to put breakpoints:

    public override int SaveChanges()
    {
        try
        {
            return base.SaveChanges();
        }
        catch (DbEntityValidationException e)
        {
            foreach (var eve in e.EntityValidationErrors)
            {
                Debug.WriteLine(@"Entity of type ""{0}"" in state ""{1}"" 
                   has the following validation errors:",
                    eve.Entry.Entity.GetType().Name, 
                    eve.Entry.State);
                foreach (var ve in eve.ValidationErrors)
                {
                    Debug.WriteLine(@"- Property: ""{0}"", Error: ""{1}""",
                        ve.PropertyName, ve.ErrorMessage);
                }
            }
            throw;
        }
        catch(DbUpdateException e)
        {
           //Add your code to inspect the inner exception and/or
           //e.Entries here.
           //Or just use the debugger.
           //Added this catch (after the comments below) to make it more obvious 
           //how this code might help this specific problem
        }
        catch (Exception e)
        {
            Debug.WriteLine(e.Message);
            throw;
        }
    }

Reference:

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details



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