.Net Core 2 - EF Core Error handling Save changes

asp.net-core asp.net-core-2.0 c# entity-framework entity-framework-core

Question

I'm used with EF6 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 is an expected error from EF if the object save is invalid. Now that I'm on a new .NET Core 2 project and I need to know what is the Expected entity validation error type in EF Core.

1
20
4/20/2019 9:32:35 AM

Accepted Answer

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.

28
9/26/2017 8:06:21 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow