Class-Level Model Validation with EF Code First and ASP.NET MVC 3
page 3 of 7
by Scott Guthrie
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 31355/ 57

Automatic Validation Enforcement

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():


View Entire Article

User Comments

No comments posted yet.

Product Spotlight
Product Spotlight 

Community Advice: ASP | SQL | XML | Regular Expressions | Windows

©Copyright 1998-2024  |  Page Processed at 2024-05-25 9:43:09 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search