c# 对一个或多个实体的验证失败。有关详细信息,请参见“EntityValidationErrors”属性。

本文介绍了解决Entity Framework中出现的EntityValidationErrors问题的方法。通过使用快速监视窗口或直接访问异常对象,可以找到验证失败的具体原因,进而定位并解决数据库操作中的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Validation failed for one or more entities. See ‘EntityValidationErrors’ property for more details.
当你遇到这个的时候你会发现,EntityValidationErrors里面没有什么东西({System.Data.Entity.Validation.DbEntityValidationResult}).
并不能让我们知道究竟是什么错误导致无法操作数据库.那么我们如何能知道错误在那呢:

While you are in debug mode within the catch {…} block open up the “QuickWatch” window (ctrl+alt+q) and paste in there:

((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.

For Visual 2012+ users who care only about the first error and might not have a catch block, you can even do:

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

For those not referencing System.Linq and using immediate window:

System.Linq.Enumerable.ToList(System.Linq.Enumerable.ToList(‌​((System.Data.Entity‌​.Validation.DbEntity‌​ValidationException)‌​$exception).EntityVa‌​lidationErrors)[0].V‌​alidationErrors)[0].‌​ErrorMessage

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);
        }
    }
}

The best solution in my opinion, is to handle this kind of errors in a centralized way.

just add this class to the main DbContext class :

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);
    }
}

来自 http://stackoverflow.com/questions/5345890/getting-exact-error-type-in-from-dbvalidationexception

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值