try
{
// Your code...
// Could also be before try if you know the exception occurs in SaveChanges
context.SaveChanges();
}
//在应用程序中,用下面的版本,调试,查看errMsg
catch (DbEntityValidationException e)
{
string errMsg = string.Empty;
foreach (var eve in e.EntityValidationErrors)
{
errMsg += string.Format("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)
{
errMsg += string.Format("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
//在控制台,则直接输出
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;
}Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
最新推荐文章于 2021-11-01 11:12:05 发布
本文介绍如何在使用Entity Framework Core时捕获并处理DbEntityValidationException异常。通过详细示例展示了如何在不同环境下(如控制台应用和Web应用)进行有效的错误信息收集与展示。
6672

被折叠的 条评论
为什么被折叠?



