DataAnnotation attributes provides an easy way to validate
individual property values on your model classes.
Several people have asked - “Does EF Code First also support
a way to implement class-level validation methods on model objects, for
validation rules than need to span multiple property values?” It does –
and one easy way you can enable this is by implementing the IValidatableObject
interface on your model classes.
IValidatableObject.Validate() Method
Below is an example of using the IValidatableObject
interface (which is built-into .NET 4 within the
System.ComponentModel.DataAnnotations namespace) to implement two custom
validation rules on a Product model class. The two rules ensure that:
New units can’t be ordered if the Product is in a
discontinued state
New units can’t be ordered if there are already more than
100 units in stock
We will enforce these business rules by implementing the
IValidatableObject interface on our Product class, and by implementing its
Validate() method like so:
The IValidatableObject.Validate() method can apply
validation rules that span across multiple properties, and can yield back
multiple validation errors. Each ValidationResult returned can supply both an
error message as well as an optional list of property names that caused
the violation (which is useful when displaying error messages within UI).