最簡單的解決方案是在您的實體類上覆蓋SaveChanges
。您可以捕獲DbEntityValidationException
,打開實際的錯誤並使用改進的消息創建新的DbEntityValidationException
。
- 在SomethingSomething.Context.cs文件旁邊創建一個部分類。
- 使用此帖子底部的代碼。
- 就是這樣。您的實現將自動使用重寫SaveChanges而不需要任何重構工作。
你的異常消息現在看起來像這樣:
System.Data.Entity.Validation.DbEntityValidationException:驗證 失敗的一個或多個實體。有關更多詳細信息,請參閱「EntityValidationErrors」屬性 。驗證錯誤爲:字段PhoneNumber 必須是最大長度爲'12'的字符串或數組類型; 姓氏字段是必需的。
您可以從DbContext
繼承任何類刪除重寫的SaveChanges:
public partial class SomethingSomethingEntities
{
public override int SaveChanges()
{
try
{
return base.SaveChanges();
}
catch (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);
// Throw a new DbEntityValidationException with the improved exception message.
throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
}
}
}
的DbEntityValidationException
還包含導致驗證錯誤的實體。所以如果你需要更多的信息,你可以改變上面的代碼來輸出關於這些實體的信息。
參見:http://devillers.nl/improving-dbentityvalidationexception/
生成的實體類已經從DbContext繼承,因此您不必在分部類上再次添加它。通過將其添加到部分類中,您不會破壞或更改任何內容。事實上,如果你從DbContext添加繼承,Resharper會建議你刪除它:「在其他部分已經指定了」Base type'DbContext'「。 – 2013-10-10 05:49:06
爲什麼這不是SaveChanges的默認行爲? – 2015-06-17 18:59:36
「爲什麼這不是SaveChanges的默認行爲?」 - 這是一個非常好的問題。這是一個驚人的解決方案,它節省了我幾個小時!我不得不拋出使用System.Linq;' – 2015-09-15 11:53:46