Entity Framework #3–my scattered notes

When using Entity Framework 4.x Code First you can put your validation code in Data Annotations or inside the DbContext class (this is my preferred mode).

It’s possible to override the virtual method ValidateEntity exposed by the DbContext class and then define your own validation logic in one place.

This method is called once for each distinct entity being modified in your context, and it provides an opportunity for developers to stop the entity update process when some properties are in invalid state.

Here’s an example:

This code will be invoked only if the “ValidateOnSaveEnabled” property of the class DbContextConfiguration is set to true.