Chapter 6. Validating with the Validation API

Developers often spend a lot of time writing validation logic in their applications. Many of the rules for validation are built into their classes, but .NET can’t magically verify those rules. Code First allows you to apply some rules directly to properties using Data Annotations or the Fluent API. For example, you can specify the maximum length of a string or the fact that a particular property is required (i.e., can’t be null).

Another type of rule that your model describes is relationship constraints. For example, in our model, a Lodging is required to have a related Destination. Entity Framework has always checked that relationship constraint rules are met before it will push inserts, updates, or deletes to the database.

The DbContext adds to this existing validation with the new Validation API that is associated with the DbContext. Using the Validation API, the DbContext can automatically (or on demand) validate all of the rules that you have defined using mechanisms that the validation will recognize. The API takes advantage of features that already exist in .NET 4—ValidationAttributes and the IValidatableObject. This integration is a great benefit to developers. Not only does it mean that you can leverage existing experience if you’ve worked with the features already, but it also means that Entity Framework validation can flow into other tools that use this class or interface.

Validation in the data layer is an important element ...

Get Programming Entity Framework: DbContext now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.