来自EntityFramework上下文的SaveChanges()无声地失败

时间:2014-06-30 21:46:42

标签: c# .net entity-framework entity-framework-6

我正在使用数据库'向导'设置中的Entity Framework 6.1模型。 当我从我的上下文创建一个Business对象然后尝试添加附件然后SaveChanges()没有任何反应。有跟踪模式吗?或者其他什么我可以转过来看看幕后真的发生了什么。

简单示例:

 var fb = _context.Business.Create();
 //fb.Id exists and is an int but it is auto incr in the db
 fb.Name = ub.ACCOUNT_NAME;
 fb.ServiceManager = ub.SERVICE_MANAGER;
 fb.AccountManager = ub.ACCOUNT_MANAGER;
 fb.SalesPerson = ub.SALESPERSON;
 fb.Created = DateTime.UtcNow;
 fb.Updated = DateTime.UtcNow;
 _context.Add(fb);
 _context.SaveChanges();

3 个答案:

答案 0 :(得分:6)

我发现捕获EF错误的最佳方法是重写下面的SaveChange方法。如果你有一个居中的地方来恢复日志(比如log4net),该函数将能够将其插入那里。

public partial class Business
{
    /// <summary>Override the SaveChange to return better error messages</summary>
    public override int SaveChanges()
    {
        try {
            return base.SaveChanges();
        }
        catch (System.Data.Entity.Validation.DbEntityValidationException ex) {
            // Retrieve the error messages as a list of strings.
            var errorMessages = ex.EntityValidationErrors
                    .SelectMany(x => x.ValidationErrors)
                    .Select(x => x.ErrorMessage);

            // Join the list to a single string.
            var fullErrorMessage = string.Join("; ", errorMessages);

            // Combine the original exception message with the new one.
            var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);

            // Add some logging with log4net here


            // Throw a new DbEntityValidationException with the improved exception message.
            throw new System.Data.Entity.Validation.DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);

        }
    }

答案 1 :(得分:0)

您是否尝试过检查验证错误?

这是我在我的一个新类中使用的try块和验证方法,因此将其视为代码示例,而不是100%经过测试的解决方案,因为我仍在进行一些单元测试:

public List<string> ValidationErrorList = new List<string>();


try
{
  _context.SaveChanges();
}
catch (Exception)
{
  GetErrors(_context);
}

private void GetErrors(System.Data.Entity.DbContext context)
{

  IEnumerable<System.Data.Entity.Validation.DbEntityValidationResult> ve;

  ve = context.GetValidationErrors();
  ValidationErrorList.Clear();

  foreach (var vr in ve)
  {
    if (vr.IsValid == false)
    {
      foreach (var e in vr.ValidationErrors)
      {
        var errorMessage = e.PropertyName.Trim() + " : " +
                           e.ErrorMessage;
        ValidationErrorList.Add(errorMessage);
      }
    }
  }
}

虽然上面的示例仅在触发异常时调用GetErrors方法,但您可能还想尝试在SaveChanges()之后立即调用它,以查看是否存在未引发异常的验证错误。

答案 2 :(得分:0)

您是否尝试过创建新的Business对象并将其添加进来?而不是先创建一个?

 var fb = new Business();
 //fb.Id exists and is an int but it is auto incr in the db
 fb.Name = ub.ACCOUNT_NAME;
 fb.ServiceManager = ub.SERVICE_MANAGER;
 fb.AccountManager = ub.ACCOUNT_MANAGER;
 fb.SalesPerson = ub.SALESPERSON;
 fb.Created = DateTime.UtcNow;
 fb.Updated = DateTime.UtcNow;
 _context.Business.Add(fb);
 _context.SaveChanges();