Entity Framework Validation

By : Micah
Source: Stackoverflow.com
Question!

I'm getting ready to start a new project and I've been researching the entity framework. My question is what is the best strategy for validating the entities? Other projects I've worked on have used attributes for most of the validation, but obviously this is not possible in the entity framework. Is the only way to do this by handling the partial methods in the property setters? All advice is much appreciated.

By : Micah


Answers

This article describes how to integrate Validation Application Block with Entity Framework. It might be of some help.

By : Steven


Consider implementing IValidatableObject in your entities.

By : Kamran


We have overrident the object context and intercept the SaveChanges() method

public abstract class ValidationObjectContext : ObjectContext{
    ...

    public override int SaveChanges(SaveOptions options){
        ValidateEntities();
        return base.SaveChanges(options);
    }

}

That way the validation is left until the last minute before the connections are made but after you are (expecting) to be happy with the graph and ready to commit, (as opposed to other options to validation on any change, since some complex rules like those we have are only valid after several properties are set.). We have two levels of validation, Basic Property validation, things like string length, nullability etc. And Business Logic validation, which might require checking rules across multiple objects, possibly hitting the database to confirm.

By : Rob


This video can help you solving your question :)
By: admin