EF Code-First (starting with CTP5) now automatically invokes
the Validate() method when a model object that implements the
IValidatableObject interface is saved. You do not need to write any code
to cause this to happen – this support is now enabled by default.
This new support means that the below code – which violates
one of our above business rules – will automatically throw an exception (and
abort the transaction) when we call the "SaveChanges()" method on our
Northwind DbContext:
In addition to reactively handling validation exceptions, EF
Code First also allows you to proactively check for validation errors.
Starting with CTP5, you can call the "GetValidationErrors()" method
on the DbContext base class to retrieve a list of validation errors within the
model objects you are working with. GetValidationErrors() will return a
list of all validation errors – regardless of whether they are generated via
DataAnnotation attributes or by an IValidatableObject.Validate()
implementation.
Below is an example of proactively using the
GetValidationErrors() method to check (and handle) errors before trying to call
SaveChanges():