3

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);
            }
        }
    }
3
  • 1. Where is the exception, you have more than one. SaveChanges call here? 2. What is the full exception message? Commented Nov 28, 2016 at 13:51
  • You should debug your code and look at the InnerException, it will give you a better idea of what the issue is. I suspect it's probably multiple entities with the same Id (duplicate key) Commented Nov 28, 2016 at 13:54
  • Note that "overlaydb1" is not added to db.overlayData. You are adding "overlaydb" twice. Commented Nov 28, 2016 at 13:54

1 Answer 1

3

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;
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.