.NET Core 2 - EF Core Error handling Save changes

22,487

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


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

Share:
22,487

Related videos on Youtube

Jins Peter
Author by

Jins Peter

Week days: I'm trying to figure out why some code is not working or doing some magic coding in C# or TypeScript. Week Nights: I'm eating, sleeping, browsing or watching a TV series. Weekends: I'm at the cinema or chilling with friends. COVID-19: Just the indoor stuff from all the above.

Updated on June 22, 2021

Comments

  • Jins Peter
    Jins Peter almost 3 years

    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 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?

    • DavidG
      DavidG over 6 years
      Did you think of trying to see what exception is thrown?
    • Dmitry
      Dmitry over 6 years
      "Exception" is always "unexpected". If you "expect" some "exceptional situation" (BTW, why you don't prevent it?) - it's your app-specific.
  • Chris Bordeman
    Chris Bordeman over 5 years
    Doesn't do referential integrity, just data annotation style validations.
  • James White
    James White about 5 years
    There is also a TryValidateObject which lets you collect the errors without throwing an excepton.
  • dan
    dan over 3 years
    If you need to include additional validations such as MinLength you may have to add the validateAllProperties bool parameter as: Validator.ValidateObject(entity, validationContext, validateAllProperties: true)