DbEntityValidationException - 如何轻松判断导致错误的原因? [英] DbEntityValidationException - How can I easily tell what caused the error?

查看:16
本文介绍了DbEntityValidationException - 如何轻松判断导致错误的原因?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用实体框架的项目.在我的 DbContext 上调用 SaveChanges 时,出现以下异常:

<块引用>

System.Data.Entity.Validation.DbEntityValidationException:验证一个或多个实体失败.请参阅EntityValidationErrors"属性了解更多详情.

这一切都很好,但我不想每次发生此异常时都附加调试器.此外,在生产环境中,我无法轻松附加调试器,因此我必须竭尽全力重现这些错误.

如何查看隐藏在 DbEntityValidationException 中的详细信息?

解决方案

最简单的解决方案是覆盖实体类上的 SaveChanges.您可以捕获 DbEntityValidationException,解开实际错误并使用改进的消息创建一个新的 DbEntityValidationException.

  1. 在您的Something.Context.cs 文件旁边创建一个分部类.
  2. 使用本文底部的代码.
  3. 就是这样.您的实现将自动使用覆盖的 SaveChanges,无需任何重构工作.

您的异常消息现在将如下所示:

<块引用>

System.Data.Entity.Validation.DbEntityValidationException:验证一个或多个实体失败.请参阅EntityValidationErrors"属性更多细节.验证错误是:字段电话号码必须是最大长度为12"的字符串或数组类型;这姓氏字段是必需的.

您可以在继承自 DbContext 的任何类中删除覆盖的 SaveChanges:

公共部分类SomethingSomethingEntities{公共覆盖 int SaveChanges(){尝试{返回 base.SaveChanges();}捕获(DbEntityValidationException 前){//以字符串列表的形式检索错误消息.var errorMessages = ex.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.ErrorMessage);//将列表加入单个字符串.var fullErrorMessage = string.Join("; ", errorMessages);//将原始异常消息与新异常消息合并.var exceptionMessage = string.Concat(ex.Message, " 验证错误为:", fullErrorMessage);//使用改进的异常消息抛出一个新的 DbEntityValidationException.throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);}}}

DbEntityValidationException 还包含导致验证错误的实体.因此,如果您需要更多信息,可以更改上述代码以输出有关这些实体的信息.

另见:http://devillers.nl/improving-dbentityvalidationexception/

I have a project that uses Entity Framework. While calling SaveChanges on my DbContext, I get the following exception:

System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

This is all fine and dandy, but I don't want to attach a debugger every time this exception occurs. More over, in production environments I cannot easily attach a debugger so I have to go to great lengths to reproduce these errors.

How can I see the details hidden within the DbEntityValidationException?

解决方案

The easiest solution is to override SaveChanges on your entities class. You can catch the DbEntityValidationException, unwrap the actual errors and create a new DbEntityValidationException with the improved message.

  1. Create a partial class next to your SomethingSomething.Context.cs file.
  2. Use the code at the bottom of this post.
  3. That's it. Your implementation will automatically use the overriden SaveChanges without any refactor work.

Your exception message will now look like this:

System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. The validation errors are: The field PhoneNumber must be a string or array type with a maximum length of '12'; The LastName field is required.

You can drop the overridden SaveChanges in any class that inherits from DbContext:

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);
        }
    }
}

The DbEntityValidationException also contains the entities that caused the validation errors. So if you require even more information, you can change the above code to output information about these entities.

See also: http://devillers.nl/improving-dbentityvalidationexception/

这篇关于DbEntityValidationException - 如何轻松判断导致错误的原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆