8

我收到此错误:

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

当我尝试使用Update-Database包管理器控制台中的命令更新数据库时。

如何将线条写入 Visual Studio 的输出窗口?

我试过了:

try
{
    context.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException e)
{
    foreach (var eve in e.EntityValidationErrors)
    {
        System.Diagnostics.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)
        {
            System.Diagnostics.Debug.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                ve.PropertyName, ve.ErrorMessage);
        }
    }
    throw;
}

但这没有用。关于如何调试它的任何其他建议?

4

2 回答 2

21

我不知道为什么写入 VS 输出窗口不起作用以及如何使它起作用。但作为最后的手段,只需将错误写入一个文本文件,该文件应该独立于您拥有的应用程序类型:

try
{
    context.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException e)
{
    var outputLines = new List<string>();
    foreach (var eve in e.EntityValidationErrors)
    {
        outputLines.Add(string.Format(
            "{0}: Entity of type \"{1}\" in state \"{2}\" has the following validation errors:",
            DateTime.Now, eve.Entry.Entity.GetType().Name, eve.Entry.State));
        foreach (var ve in eve.ValidationErrors)
        {
            outputLines.Add(string.Format(
                "- Property: \"{0}\", Error: \"{1}\"",
                ve.PropertyName, ve.ErrorMessage));
        }
    }
    //Write to file
    System.IO.File.AppendAllLines(@"c:\temp\errors.txt", outputLines);
    throw;

    // Showing it on screen
    throw new Exception( string.Join(",", outputLines.ToArray()));

}
于 2013-05-17T23:01:40.023 回答
4

您可以将其传递到异常堆栈,如下所示。

try
{
    _dbContext.SaveChanges();
}
catch (DbEntityValidationException dbValEx)
{
   var outputLines = new StringBuilder();
   foreach (var eve in dbValEx.EntityValidationErrors)
   {
     outputLines.AppendFormat("{0}: Entity of type \"{1}\" in state \"{2}\" has the following validation errors:"
       ,DateTime.Now, eve.Entry.Entity.GetType().Name, eve.Entry.State);

     foreach (var ve in eve.ValidationErrors)
     {
       outputLines.AppendFormat("- Property: \"{0}\", Error: \"{1}\""
        ,ve.PropertyName, ve.ErrorMessage);
     }
   }

 throw new DbEntityValidationException(string.Format("Validation errors\r\n{0}"
  ,outputLines.ToString()), dbValEx);
}
于 2013-11-18T16:56:12.247 回答