首页 > 数据库技术 > 详细

How to handle the DbEntityValidationException in C#

时间:2016-07-07 09:39:57      阅读:321      评论:0      收藏:0      [点我收藏+]

When I want to use db.SaveChanges(), if some of the columns got validation error and throw DbEntityValidationException, and you can‘t tell which one is wrong, maybe try this way will help.

You can extract all the information from the DbEntityValidationException with the following code (you need to add the namespaces: System.Data.Entity.Validation and System.Diagnostics to your using list):

 

try
{
    db.SaveChanges();
}
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);
        }
    }
}

Using debug tools, set breakpoints, then you will see the detail error message during the foreach loop.

How to handle the DbEntityValidationException in C#

原文:http://www.cnblogs.com/ivyfu/p/5648758.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!