热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

从DbValidationException获取准确的错误类型-GettingexacterrortypeinfromDbValidationException

IhavethesituationwhereIminitializingmymodelinDatabaseInitializer()forEF4.1andgetthi

I have the situation where I'm initializing my model in DatabaseInitializer() for EF 4.1 and get this annoying error "Validation failed for one or more entities. See 'EntityValidationErrors' property for more details." So, I go to this EntityValidationErrors and there is a field {System.Data.Entity.Validation.DbEntityValidationResult} which gives me no information at all about what field it was unable to initialize. Is there a way to get more info about this error?

我有这样一种情况:我正在为EF 4.1在DatabaseInitializer()中初始化我的模型,却发现一个或多个实体的这个烦人的错误“验证失败了。有关更多细节,请参见'EntityValidationErrors'属性。因此,我转到EntityValidationErrors,这里有一个字段{System.Data.Entity.Validation。DbEntityValidationResult},它对无法初始化的字段没有任何信息。是否有办法获得关于这个错误的更多信息?

To clear things out:

明确的事情:

I know how to fix the string length problem. What I'm asking is how do I get the exact field name that is breaking the model.

我知道如何解决字符串长度问题。我要问的是,如何得到一个准确的字段名来打破模型。

5 个解决方案

#1


361  

While you are in debug mode within the catch {...} block open up the "QuickWatch" window (ctrl+alt+q) and paste in there:

当您处于调试模式的catch{…> > > > > > > > > > > > > > > > >打开“QuickWatch”窗口(ctrl+alt+q),粘贴在那里:

((System.Data.Entity.Validation.DbEntityValidationException)ex).EntityValidationErrors

This will allow you to drill down into the ValidationErrors tree. It's the easiest way I've found to get instant insight into these errors.

这将允许您深入到ValidationErrors树。这是我发现的最简单的方法,可以立即洞察这些错误。

For Visual 2012+ users who care only about the first error and might not have a catch block, you can even do:

对于Visual 2012+只关心第一个错误而可能没有捕获块的用户,您甚至可以这样做:

((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors.First().ValidationErrors.First().ErrorMessage

#2


122  

You could try this in a try/catch block?

你可以试试这个吗?

catch (DbEntityValidationException dbEx)
{
    foreach (var validationErrors in dbEx.EntityValidationErrors)
    {
        foreach (var validationError in validationErrors.ValidationErrors)
        {
            Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
        }
    }
}

#3


9  

The best solution in my opinion, is to handle this kind of errors in a centralized way.

在我看来,最好的解决办法是集中处理这类错误。

just add this method to the main DbContext class :

只需将此方法添加到主DbContext类:

public override int SaveChanges()
{
    try
    {
        return base.SaveChanges();
    }
    catch (DbEntityValidationException ex)
    {
        string errorMessages = string.Join("; ", ex.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.PropertyName + ": " + x.ErrorMessage));
        throw new DbEntityValidationException(errorMessages);
    }
}

This will overwrite your context's SaveChanges() method and you'll get a comma separated list containing all the entity validation errors.

这将覆盖您的上下文的SaveChanges()方法,您将得到一个逗号分隔的列表,其中包含所有的实体验证错误。

hope this is helpful.

希望这是有帮助的。

#4


4  

Well, I had same problem. My model worked good in EF CTP5 but failed to build in 4.1 with the same error ""Validation failed for one or more entities" when I tried to initalize it. I figured out that I had property:

我也有同样的问题。我的模型在EF CTP5中运行良好,但在4.1中构建失败,当我试图对它进行调整时,“一个或多个实体的验证失败”也出现了同样的错误。我发现我有财产:

public string Comment {get; set;}

Then in seed method in overrided initializer, I had quite a bit long (about 600 letters) comment.

然后在overrided初始化器的种子方法中,我有相当长的(大约600个字母)注释。

I think the point is: in EF 4.1 you have to set data annotations explicitly in some cases. For me, setting:

我认为关键在于:在EF 4.1中,在某些情况下,必须显式地设置数据注释。对我来说,设置:

[StringLength(4000)] 
public string Comment {get; set;}

helped. It's weird since CTP5 had no problems with that.

帮助。这很奇怪,因为CTP5没有问题。

#5


1  

I found it useful to create a SaveChanges wrapper which makes the EntityValidationErrors more readable:

我发现创建一个SaveChanges包装器非常有用,它使EntityValidationErrors更加可读:

Public Sub SaveChanges(entities As Entities)

    Try
        entities.SaveChanges()

    Catch ex As DbEntityValidationException

        Dim msg As New StringBuilder
        msg.AppendLine(ex.Message)

        For Each vr As DbEntityValidationResult In ex.EntityValidationErrors
            For Each ve As DbValidationError In vr.ValidationErrors
                msg.AppendLine(String.Format("{0}: {1}", ve.PropertyName, ve.ErrorMessage))
            Next
        Next

        Throw New DbEntityValidationException(msg.ToString, ex.EntityValidationErrors, ex)

    End Try

End Sub

and then changed 'entities.SaveChanges()' to 'SaveChanges(entities)' in my entire project

然后更改了“entities.SaveChanges()”到“SaveChanges(实体)”在我的整个项目中。


推荐阅读
  • 欢乐的票圈重构之旅——RecyclerView的头尾布局增加
    项目重构的Git地址:https:github.comrazerdpFriendCircletreemain-dev项目同步更新的文集:http:www.jianshu.comno ... [详细]
  • 集合的遍历方式及其局限性
    本文介绍了Java中集合的遍历方式,重点介绍了for-each语句的用法和优势。同时指出了for-each语句无法引用数组或集合的索引的局限性。通过示例代码展示了for-each语句的使用方法,并提供了改写为for语句版本的方法。 ... [详细]
  • 1Lock与ReadWriteLock1.1LockpublicinterfaceLock{voidlock();voidlockInterruptibl ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • 本文主要解析了Open judge C16H问题中涉及到的Magical Balls的快速幂和逆元算法,并给出了问题的解析和解决方法。详细介绍了问题的背景和规则,并给出了相应的算法解析和实现步骤。通过本文的解析,读者可以更好地理解和解决Open judge C16H问题中的Magical Balls部分。 ... [详细]
  • MyBatis多表查询与动态SQL使用
    本文介绍了MyBatis多表查询与动态SQL的使用方法,包括一对一查询和一对多查询。同时还介绍了动态SQL的使用,包括if标签、trim标签、where标签、set标签和foreach标签的用法。文章还提供了相关的配置信息和示例代码。 ... [详细]
  • MongoDB用户验证auth的权限设置及角色说明
    本文介绍了MongoDB用户验证auth的权限设置,包括readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase、cluster相关的权限以及root权限等角色的说明和使用方法。 ... [详细]
  • WPF开发心率检测大数据曲线图的高性能实现方法
    本文介绍了在WPF开发中实现心率检测大数据曲线图的高性能方法。作者尝试过使用Canvas和第三方开源库,但性能和功能都不理想。最终作者选择使用DrawingVisual对象,并结合局部显示的方式实现了自己想要的效果。文章详细介绍了实现思路和具体代码,对于不熟悉DrawingVisual的读者可以去微软官网了解更多细节。 ... [详细]
  • VueCLI多页分目录打包的步骤记录
    本文介绍了使用VueCLI进行多页分目录打包的步骤,包括页面目录结构、安装依赖、获取Vue CLI需要的多页对象等内容。同时还提供了自定义不同模块页面标题的方法。 ... [详细]
  • 解决.net项目中未注册“microsoft.ACE.oledb.12.0”提供程序的方法
    在开发.net项目中,通过microsoft.ACE.oledb读取excel文件信息时,报错“未在本地计算机上注册“microsoft.ACE.oledb.12.0”提供程序”。本文提供了解决这个问题的方法,包括错误描述和代码示例。通过注册提供程序和修改连接字符串,可以成功读取excel文件信息。 ... [详细]
  • Todayatworksomeonetriedtoconvincemethat:今天在工作中有人试图说服我:{$obj->getTableInfo()}isfine ... [详细]
  • php缓存ri,浅析ThinkPHP缓存之快速缓存(F方法)和动态缓存(S方法)(日常整理)
    thinkPHP的F方法只能用于缓存简单数据类型,不支持有效期和缓存对象。S()缓存方法支持有效期,又称动态缓存方法。本文是小编日常整理有关thinkp ... [详细]
  • 本文介绍了在实现了System.Collections.Generic.IDictionary接口的泛型字典类中如何使用foreach循环来枚举字典中的键值对。同时还讨论了非泛型字典类和泛型字典类在foreach循环中使用的不同类型,以及使用KeyValuePair类型在foreach循环中枚举泛型字典类的优势。阅读本文可以帮助您更好地理解泛型字典类的使用和性能优化。 ... [详细]
  • 判断编码是否可立即解码的程序及电话号码一致性判断程序
    本文介绍了两个编程题目,一个是判断编码是否可立即解码的程序,另一个是判断电话号码一致性的程序。对于第一个题目,给出一组二进制编码,判断是否存在一个编码是另一个编码的前缀,如果不存在则称为可立即解码的编码。对于第二个题目,给出一些电话号码,判断是否存在一个号码是另一个号码的前缀,如果不存在则说明这些号码是一致的。两个题目的解法类似,都使用了树的数据结构来实现。 ... [详细]
  • 本文介绍了如何使用OpenXML按页码访问文档内容,以及在处理分页符和XML元素时的一些挑战。同时,还讨论了基于页面的引用框架的局限性和超越基于页面的引用框架的方法。最后,给出了一个使用C#的示例代码来按页码访问OpenXML内容的方法。 ... [详细]
author-avatar
Jie
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有