views:

28

answers:

1

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?

A: 

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!

Craig Stuntz
That is quite similar to what I have :) Except I don't have the validation in each separate entity. It felt like it was violating SRP.
uriDium
You can do it however you want -- using an external validator is no harder. The point is that if it takes more than a couple lines of code, well, it shouldn't.
Craig Stuntz