savechanges方法中的'System.Data.Entity.Infrastructure.DbUpdateException'

时间:2016-11-28 13:49:26

标签: c# entity-framework

我写了一个相当简单的代码(基于WCF和Windows窗体的客户端服务器)。我试图更新数据库,以便我可以测试我的代码,我得到一个例外:

  发生了'System.Data.Entity.Infrastructure.DbUpdateException'   EntityFramework.dll   任何想法如何解决?

这是我的代码:

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);
            }
        }
    }

1 个答案:

答案 0 :(得分:3)

编写一个调用SaveChanges()的方法并在那里进行错误检查。这将为您提供描述性错误,您可以找出导致错误的原因。此外,还有一些错误,所有错误都需要不同的处理。这是我的。我已经包含了另一个非常有用的方法,它获取内部异常并以递归方式执行。那个列在底部。我希望这会有所帮助:

    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));

        }
    }

以下是获取内部异常的方法......非常有用

    /// <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;
    }