Back after a few weeks. For those who don’t know, this series of posts is dedicated to bringing some of the futures that existed in Entity Framework but were dropped in Core. You can find the first post here and the second here.
This time, an often forgotten feature that didn’t made it to Core: entity validation. Most of the posts that talk about what’s new usually forget about validation having been left out.
In a nutshell, Entity Framework used to validate entities according to the System.ComponentModel.DataAnnotations API:
It’s simple to get these back, though. All you need to do is override SaveChanges and plug in the validation code for all new and modified entries:
The key here is the Validator class: it knows how to perform all these validations, including finding all validation attributes in the class and in each property. In case of an error, we just throw a ValidationException with the error message, and the saving is aborted.