我有一个使用实体框架的项目。而在我的DbContext上调用SaveChanges时,我得到了以下异常:

System.Data.Entity.Validation.DbEntityValidationException:验证 一个或多个实体失败。参见'EntityValidationErrors'属性 欲知详情。

这一切都很好,但我不希望每次发生此异常时都附加调试器。此外,在生产环境中,我不能轻易地附加调试器,因此我必须竭尽全力重现这些错误。

我如何才能看到隐藏在DbEntityValidationException中的细节?


当前回答

对于Azure函数,我们使用这个简单的扩展Microsoft.Extensions.Logging.ILogger

public static class LoggerExtensions
{
    public static void Error(this ILogger logger, string message, Exception exception)
    {
        if (exception is DbEntityValidationException dbException)
        {
            message += "\nValidation Errors: ";
            foreach (var error in dbException.EntityValidationErrors.SelectMany(entity => entity.ValidationErrors))
            {
                message += $"\n * Field name: {error.PropertyName}, Error message: {error.ErrorMessage}";
            }
        }

        logger.LogError(default(EventId), exception, message);
    }
}

以及示例用法:

try
{
    do something with request and EF
}
catch (Exception e)
{
    log.Error($"Failed to create customer due to an exception: {e.Message}", e);
    return await StringResponseUtil.CreateResponse(HttpStatusCode.InternalServerError, e.Message);
}

其他回答

当您在catch{…打开“QuickWatch”窗口(ctrl+alt+q)并粘贴在那里:

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

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

对于Visual 2012+用户,他们只关心第一个错误,可能没有catch块,你甚至可以这样做:

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

Actually, this is just the validation issue, EF will validate the entity properties first before making any changes to the database. So, EF will check whether the property's value is out of range, like when you designed the table. Table_Column_UserName is varchar(20). But, in EF, you entered a value that longer than 20. Or, in other cases, if the column does not allow to be a Null. So, in the validation process, you have to set a value to the not null column, no matter whether you are going to make the change on it. I personally, like the Leniel Macaferi answer. It can show you the detail of the validation issues

要查看EntityValidationErrors集合,请将以下Watch表达式添加到Watch窗口。

((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors

我使用的是visual studio 2013

对于Azure函数,我们使用这个简单的扩展Microsoft.Extensions.Logging.ILogger

public static class LoggerExtensions
{
    public static void Error(this ILogger logger, string message, Exception exception)
    {
        if (exception is DbEntityValidationException dbException)
        {
            message += "\nValidation Errors: ";
            foreach (var error in dbException.EntityValidationErrors.SelectMany(entity => entity.ValidationErrors))
            {
                message += $"\n * Field name: {error.PropertyName}, Error message: {error.ErrorMessage}";
            }
        }

        logger.LogError(default(EventId), exception, message);
    }
}

以及示例用法:

try
{
    do something with request and EF
}
catch (Exception e)
{
    log.Error($"Failed to create customer due to an exception: {e.Message}", e);
    return await StringResponseUtil.CreateResponse(HttpStatusCode.InternalServerError, e.Message);
}

我认为“实际的验证错误”可能包含敏感信息,这可能是微软选择将它们放在另一个地方(属性)的原因。这里标出的解决办法是可行的,但应谨慎使用。

我更喜欢创建一个扩展方法。还有更多的原因:

保留原始堆栈跟踪 遵循开放/封闭原则。:我可以对不同类型的日志使用不同的消息) 在生产环境中,可能存在其他位置(例如。: other dbcontext),其中DbEntityValidationException可能被抛出。