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?
Entity Framework Core Save Changes to the database using the SaveChanges method of DbContext. When we use the SaveChanges it prepares the corresponding insert , update , delete queries. It then wraps them in a Transaction and sends them to the database. If any of the queries fails all the statements are rolled back.
To configure a custom error handling page for the Production environment, call UseExceptionHandler. This exception handling middleware: Catches and logs unhandled exceptions. Re-executes the request in an alternate pipeline using the path indicated.
One of the biggest reasons not to use Entity Framework Core is that your application needs the fastest possible data access. Some applications do a lot of heavy data operations with very high-performance demands, but usually business applications don't have that high of a performance demand.
You should do validation on the UI first then handle specific errors related to Entity Framework. Now when someone tries to enter a non numeric or a number that is out of range an error will be displayed to the user before bad data is ever sent back to the controller. An error occurred sending updates to the database.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With