擴充 .Context.cs 覆寫 SaveChanges() 顯示詳細的驗證錯誤訊息
1. 在Models資料夾底下新增資料夾,建議取名Extend
2. 新增class,檔名取相同名稱方便識別,如 Model1.Context.cs
3. 檔案範例內容如下
namespace xxx.Models
{
public partial class xxxEntities
{
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, "驗證錯誤訊息: ", fullErrorMessage);
// Throw a new DbEntityValidationException with the improved exception message.
throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
}
}
}
}
參考來源
針對 entity framework core 已經沒有 DbEntityValidationException 需要換一種方式處理
try
{
return base.SaveChanges();
}
catch (DbUpdateException ex)
{
string err = "";
var failedEntries = ex.Entries;
foreach (var entry in failedEntries)
{
var entityName = entry.Metadata.Name;
var properties = entry.Properties.Where(p => p.IsModified && !p.IsTemporary);
foreach (var property in properties)
{
var propertyName = property.Metadata.Name;
err += $"\n更新欄位失敗: {entityName}.{propertyName}, 新值: {property.CurrentValue}";
}
}
throw new Exception(err,ex);
}