.NET Core 2 - EF Core 错误处理保存更改 [英] .NET Core 2 - EF Core Error handling Save changes

查看:33
本文介绍了.NET Core 2 - EF Core 错误处理保存更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我习惯了 Entity Framework 6 和我的基础存储库 Save() 看起来像这样:

I'm used to Entity Framework 6 and my base repository Save() looks like this:

public void Save()
{
    try
    {
        Context.SaveChanges();
    }
    catch (DbEntityValidationException ex)
    {
        // Do stuff
    }
    catch (Exception exception)
    {
        // Do stuff
    }
    else
    {
        throw;
    }
}

如果对象保存无效,

DbEntityValidationException 是来自实体框架的预期错误.现在我在一个新的 .NET Core 2 项目上.Entity Framework Core 中的预期实体验证错误类型是什么?

DbEntityValidationException is an expected error from Entity Framework if the object save is invalid. Now that I'm on a new .NET Core 2 project. What is the expected entity validation error type in Entity Framework Core?

推荐答案

查看 GitHub 问题,Entity Framework Core 中没有 DbEntityValidationException 等效项.有一篇博文(链接自issue #9662 on GitHub),给出了自己执行验证逻辑的代码示例,包含在此处为了完整性:

Looking through the GitHub issues, there is no DbEntityValidationException equivalent in Entity Framework Core. There's a blog post (linked from issue #9662 on GitHub), that gives a code example for performing the validation logic yourself, included here for completeness:

class MyContext : DbContext
{
    public override int SaveChanges()
    {
        var entities = from e in ChangeTracker.Entries()
                       where e.State == EntityState.Added
                           || e.State == EntityState.Modified
                       select e.Entity;
        foreach (var entity in entities)
        {
            var validationContext = new ValidationContext(entity);
            Validator.ValidateObject(entity, validationContext);
        }

        return base.SaveChanges();
    }
}

如果验证失败,

Validator.ValidateObject 将抛出 ValidationException,您可以相应地处理.

Validator.ValidateObject will throw a ValidationException if validation fails, which you can handle accordingly.

链接问题中有更多信息,以防您遇到验证属性问题.

There's a bit more information in the linked issue in case you run into issues with the validation attributes.

注意:Validator 类位于 System.ComponentModel.DataAnnotations 命名空间中.

Note: The Validator class is located in the System.ComponentModel.DataAnnotations namespace.

这篇关于.NET Core 2 - EF Core 错误处理保存更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆