Implementing Missing Features in Entity Framework Core – Part 3: Validations

Validations

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:

public class MyContext : DbContext
{
    public override int SaveChanges(bool acceptAllChangesOnSuccess)
    {
        var serviceProvider = this.GetService<IServiceProvider>();
        var items = new Dictionary<object, object>();
        
        foreach (var entry in this.ChangeTracker.Entries().Where(e => (e.State == EntityState.Added) || (e.State == EntityState.Modified))
        {
            var entity = entry.Entity;
            var context = new ValidationContext(entity, serviceProvider, items);
            var results = new List<ValidationResult>();
 
            if (Validator.TryValidateObject(entity, context, results, true) == false)
            {
                foreach (var result in results)
                {
                    if (result != ValidationResult.Success)
                    {
                        throw new ValidationException(result.ErrorMessage);
                    }
                }
            }
        }
 
        return base.SaveChanges(acceptAllChangesOnSuccess);
    }
}

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.

                             

No Comments

Add a Comment

As it will appear on the website

Not displayed

Your website