gpt4 book ai didi

c# - DbEntityValidationException - 我如何轻松判断导致错误的原因?

转载 作者:IT王子 更新时间:2023-10-29 03:29:26 24 4
gpt4 key购买 nike

我有一个使用 Entity Framework 的项目。在我的 DbContext 上调用 SaveChanges 时,出现以下异常:

System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

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

如何查看隐藏在 DbEntityValidationException 中的详细信息?

最佳答案

最简单的解决方案是覆盖实体类上的 SaveChanges。您可以捕获 DbEntityValidationException,解包实际错误并使用改进的消息创建新的 DbEntityValidationException

  1. 在您的 SomethingSomething.Context.cs 文件旁边创建一个分部类。
  2. 使用本文底部的代码。
  3. 就是这样。您的实现将自动使用覆盖的 SaveChanges,无需任何重构工作。

您的异常消息现在将如下所示:

System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. The validation errors are: The field PhoneNumber must be a string or array type with a maximum length of '12'; The LastName field is required.

您可以在继承自 DbContext 的任何类中删除重写的 SaveChanges:

public partial class SomethingSomethingEntities
{
public override int SaveChanges()
{
try
{
return base.SaveChanges();
}
catch (DbEntityValidationException ex)
{
// Retrieve the error messages as a list of strings.
var errorMessages = ex.EntityValidationErrors
.SelectMany(x => x.ValidationErrors)
.Select(x => x.ErrorMessage);
    
// Join the list to a single string.
var fullErrorMessage = string.Join("; ", errorMessages);
    
// Combine the original exception message with the new one.
var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
    
// Throw a new DbEntityValidationException with the improved exception message.
throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
}
}
}

DbEntityValidationException 还包含导致验证错误的实体。因此,如果您需要更多信息,您可以更改上述代码以输出有关这些实体的信息。

另请参阅:http://devillers.nl/improving-dbentityvalidationexception/

关于c# - DbEntityValidationException - 我如何轻松判断导致错误的原因?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15820505/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com