热门标签 | 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(实体)”在我的整个项目中。


推荐阅读
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社区 版权所有