3 回答
TA贡献1794条经验 获得超8个赞
老实说,我不知道如何检查验证错误的内容。VisualStudio向我展示了它是一个包含8个对象的数组,因此有8个验证错误。
try{
// Your code...
// Could also be before try if you know the exception occurs in SaveChanges
context.SaveChanges();}catch (DbEntityValidationException e){
foreach (var eve in e.EntityValidationErrors)
{
Console.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)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;}EntityValidationErrorsValidationErrors
编辑
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Value: \"{1}\", Error: \"{2}\"",
ve.PropertyName,
eve.Entry.CurrentValues.GetValue<object>(ve.PropertyName),
ve.ErrorMessage);
}Debug.WriteConsole.WriteLine
SaveChanges
public class FormattedDbEntityValidationException : Exception{
public FormattedDbEntityValidationException(DbEntityValidationException innerException) :
base(null, innerException)
{
}
public override string Message
{
get {
var innerException = InnerException as DbEntityValidationException;
if (innerException != null)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine();
sb.AppendLine();
foreach (var eve in innerException.EntityValidationErrors)
{
sb.AppendLine(string.Format("- Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().FullName, eve.Entry.State));
foreach (var ve in eve.ValidationErrors)
{
sb.AppendLine(string.Format("-- Property: \"{0}\", Value: \"{1}\", Error: \"{2}\"",
ve.PropertyName,
eve.Entry.CurrentValues.GetValue<object>(ve.PropertyName),
ve.ErrorMessage));
}
}
sb.AppendLine();
return sb.ToString();
}
return base.Message;
}
}}SaveChanges
public class MyContext : DbContext{
// ...
public override int SaveChanges()
{
try
{
return base.SaveChanges();
}
catch (DbEntityValidationException e)
{
var newException = new FormattedDbEntityValidationException(e);
throw newException;
}
}}Elmah在Web界面或发送的电子邮件中显示的黄色错误屏幕(如果您已经配置了的话)现在将验证细节直接显示在消息的顶部。 覆盖 Message属性在自定义异常中,而不是覆盖。 ToString()具有标准的ASP.NET“死亡黄屏幕(YSOD)”也显示此消息的好处。与Elmah相比,YSOD显然不使用 ToString(),但两者都显示 Message财产。 包装原件 DbEntityValidationException作为内部异常,可以确保原始堆栈跟踪仍然可用,并显示在Elmah和YSOD中。 通过在行上设置断点 throw newException;您可以简单地检查 newException.Message属性作为文本,而不是钻入验证集合,这有点尴尬,而且似乎对每个人都不容易工作(请参阅下面的注释)。
- 3 回答
- 0 关注
- 1707 浏览
添加回答
举报
