O'Reilly logo

Programming Entity Framework: DbContext by Rowan Miller, Julia Lerman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Specifying Type-Level Validation Rules

While there are more ways to trigger validations, let’s stick with the GetValidationResult method while we look at other ways to provide rules that the Validation API will validate. So far you’ve seen how to apply validation rules on individual properties. You can also define rules for a type that can take multiple properties into account. Two ways to create type-level validation that will be checked by the Entity Framework Validation API are by having your type implement the IValidatableObject interface or defining CustomValidationAttributes for type. This section will explore both of these options.

Using IValidatableObject for Type Validation

In addition to the ValidationAttribute, .NET 4 introduced another feature to help developers with validation logic—the IValidatableObject interface. IValidatableObject provides a Validate method to let developers (or frameworks) provide their own context from which to perform the validation.

If an entity that is being validated implements the IValidatableObject interface, the Validation API logic will recognize this, call the Validate method, and surface the results of the validation in a DbEntityValidationError.

What does IValidatableObject provide that is not satisfied with Data Annotations? The Data Annotations let you specify a limited number of rules for individual properties. With the additional Validate method, you can provide any type of logic that can be constrained to the class. What we mean by ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required