user5570680 user5570680 - 11 days ago 7
C# Question

'System.Data.Entity.Infrastructure.DbUpdateException' within savechanges method

I wrote a rather simple code (client server based on WCF and Windows form). i was trying to update the db so that i could test my code and I am getting an exception:


'System.Data.Entity.Infrastructure.DbUpdateException' occurred in
EntityFramework.dll
Any ideas how to solve it?


here is my code:

public void updateTable()
{
using (var db = new overlayDBEntities())
{
var overlaydb = new overlayData
{
DeviceId = "1111",
TimestampUTC = new DateTime(2015, 1, 1, 1, 1, 1),
OverlayData1 = "eddy and budu"
};

db.overlayData.Add(overlaydb);

try
{
db.SaveChanges();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
var overlaydb1 = new overlayData
{
DeviceId = "1111",
TimestampUTC = new DateTime(2000, 2, 2, 10, 10, 10),
OverlayData1 = "dumm2sec dumm2sec "
};

db.overlayData.Add(overlaydb);

try
{
db.SaveChanges();
}
catch (Exception ec)
{
Console.WriteLine(ec.Message);
}
}
}

Answer

Write a method that calls SaveChanges() and do your error checking in there. This will give you an error that is descriptive and you can work out what is causing the error. Also, there are several errors and all of them require different handling. This is the one I have. I have included another very useful method that I have which gets the inner exception and does it recursively. That one is listed in the bottom. I hope this helps:

    public virtual void Save()
    {

        try
        {
            _db.SaveChanges();
        }
        catch (DbEntityValidationException e)
        {
            List<String> lstErrors = new List<string>();
            foreach (var eve in e.EntityValidationErrors)
            {
                string msg = string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                    eve.Entry.Entity.GetType().Name, 
                    eve.Entry.State);

                lstErrors.Add(msg);

                foreach (var ve in eve.ValidationErrors)
                {
                    msg = string.Format("- Property: \"{0}\", Error: \"{1}\"",
                        ve.PropertyName, ve.ErrorMessage);
                    lstErrors.Add(msg);
                }
            }

            if(lstErrors != null && lstErrors.Count() > 0)
            {
                StringBuilder sb = new StringBuilder();
                foreach (var item in lstErrors)
                {
                    sb.Append(item + "; ");
                }

                throw new Exception("Repository.Save. Db Entity Validation Exception. Data not saved. Error: " + sb.ToString());

            }

            throw new Exception("Repository.Save. Db Entity Validation Exception. Data not saved. Error: " + AliKuli.Utilities.ExceptionNS.ErrorMsgClass.GetInnerException(e));
        }

        catch (NotSupportedException e)
        {

            throw new Exception("Repository.Save. Not supported Exception.  Data not saved. Error: " + AliKuli.Utilities.ExceptionNS.ErrorMsgClass.GetInnerException(e));
        }


        catch (ObjectDisposedException e)
        {

            throw new Exception("Repository.Save. Repository.Save. Object Disposed Exception.  Data not saved. Error: " + AliKuli.Utilities.ExceptionNS.ErrorMsgClass.GetInnerException(e));

        }

        catch (InvalidOperationException e)
        {
            throw new Exception("Repository.Save. Invalid Operation Exception.  Data not saved. Error: " + AliKuli.Utilities.ExceptionNS.ErrorMsgClass.GetInnerException(e));
        }

        catch (DbUpdateConcurrencyException e)
        {
            throw new Exception("Repository.Save. Db Update Concurrency Exception.  Data not saved. Error: " + AliKuli.Utilities.ExceptionNS.ErrorMsgClass.GetInnerException(e));
        }

        catch (DbUpdateException e)
        {
            throw new Exception("Repository.Save. Db Update Exception.  Data not saved. Error: " + AliKuli.Utilities.ExceptionNS.ErrorMsgClass.GetInnerException(e));
        }

        catch (EntityException e)
        {
            throw new Exception("Repository.Save. Entity Exception.  Data not saved. Error: " + AliKuli.Utilities.ExceptionNS.ErrorMsgClass.GetInnerException(e));
        }

        catch (DataException e)
        {
            throw new Exception("Repository.Save. Data  Exception.  Data not saved. Error: " + AliKuli.Utilities.ExceptionNS.ErrorMsgClass.GetInnerException(e));
        }

        catch (Exception e)
        {
            throw new Exception("Repository.Save. General Exception.  Data not saved. Error: " + AliKuli.Utilities.ExceptionNS.ErrorMsgClass.GetInnerException(e));

        }
    }

Below are the methods that get the inner exceptions... very useful

    /// <summary>
    /// This sets up the recursive function
    /// </summary>
    /// <param name="e"></param>
    /// <returns></returns>
    public static string GetInnerException(Exception e)
    {
        string innerExceptionMessage = "";
        string error = GetInnerException(e, out innerExceptionMessage);

        return error;

    }


/// <summary>
    /// This is a recursive function which recursively drills down and gets the error.
    /// </summary>
    /// <param name="e"></param>
    /// <param name="msg"></param>
    /// <returns></returns>
    private static string GetInnerException(Exception e, out string msg)
    {
        if (e.InnerException != null)
            GetInnerException(e.InnerException, out msg);
        else
            msg = e.Message;
        return msg;
    }