码迷,mamicode.com
首页 > 数据库 > 详细

How to handle the DbEntityValidationException in C#

时间:2016-07-07 09:42:37      阅读:173      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!