Is there a better way to perform validation in Entity Framework 4 than overriding SavingChanges? – Education Career Blog

It feels a little wrong to me to be doing Validation in your context which is your data layer. For the data layer to have a dependency on validation seems a little backwards. It makes more sense to me for validation to be done in business logic and once the validation is complete then persist the changes. The data layer should be able to rely on the fact that the data is valid.

The second reason I don’t really like overriding SavingChanges is that it seems very messy and gets full of code quickly. When you have a complex object graph that method is going to get very messy VERY quickly with a lot of

if (entity is MyType)
    //perform MyType validation

Third reason I don’t really like this is all the extra validator objects that I would have to pass in the constructor of the object context. I am using a DI framework but it still feels messy.

I suppose I only have this problem because I am letting people use the repositories. I could add a layer of indirection and then they would have to use some sort of DTO. The downside here is it seems like a lot of extra work. Also the constant mapping that would have to take place.

Is there anyway that you could give access to repositories and to do validation without sticking everything into one SavingChanges method?


If your code is ugly, write nicer code. 🙂

var entities = context.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified))
                                         .Select(ose => ose.Entity);
var errors   = entities.OfType<IMyValidationInterface>()
                       .SelectMany(e => e.Validate());

…and done!

Leave a Comment