3 回答

TA貢獻1794條經(jīng)驗 獲得超8個贊
老實說,我不知道如何檢查驗證錯誤的內(nèi)容。VisualStudio向我展示了它是一個包含8個對象的數(shù)組,因此有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;}
EntityValidationErrors
ValidationErrors
編輯
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.Write
Console.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界面或發(fā)送的電子郵件中顯示的黃色錯誤屏幕(如果您已經(jīng)配置了的話)現(xiàn)在將驗證細節(jié)直接顯示在消息的頂部。 覆蓋 Message
屬性在自定義異常中,而不是覆蓋。 ToString()
具有標準的ASP.NET“死亡黃屏幕(YSOD)”也顯示此消息的好處。與Elmah相比,YSOD顯然不使用 ToString()
,但兩者都顯示 Message
財產(chǎn)。 包裝原件 DbEntityValidationException
作為內(nèi)部異常,可以確保原始堆棧跟蹤仍然可用,并顯示在Elmah和YSOD中。 通過在行上設置斷點 throw newException;
您可以簡單地檢查 newException.Message
屬性作為文本,而不是鉆入驗證集合,這有點尷尬,而且似乎對每個人都不容易工作(請參閱下面的注釋)。
- 3 回答
- 0 關注
- 1661 瀏覽
添加回答
舉報