.NET Core 2 - EF Core Error handling Save changes

前端 未结 1 1759
醉话见心
醉话见心 2020-12-29 05:03

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

public void Save()
{
    try
    {
        Context.SaveChanges();
             


        
相关标签:
1条回答
  • 2020-12-29 05:45

    Looking through the Github issues, there is no DbEntityValidationException equivalent in Entity Framework Core. There's a blog (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 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.

    0 讨论(0)
提交回复
热议问题