EF Database First with ASP.NET MVC: Enhancing Data Validation
Using MVC, Entity Framework, and ASP.NET Scaffolding, you can create a web application that provides an interface to an existing database. This tutorial series shows you how to automatically generate code that enables users to display, edit, create, and delete data that resides in a database table. The generated code corresponds to the columns in the database table.
This part of the series focuses on adding data annotations to the data model to specify validation requirements.
Add data annotations
As you saw in an earlier topic, some data validation rules are automatically applied to the user input. For example, you can only provide a number for the Grade property. To specify more data validation rules, you can add data annotations to your model class. These annotations are applied throughout your web application for the specified property.
In this tutorial, you will add data annotations to restrict the length of the values provided for the FirstName, LastName, and MiddleName properties. In the database, these values are limited to 50 characters; however, in your web application that character limit is currently not enforced. If a user provides more than 50 characters for one of those values, the page will crash when attempting to save the value to the database. You will also restrict Grade to values between 0 and 4.
Open the Student.cs file in the Models folder. Add the following highlighted code to the class.
namespace ContosoSite.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; public partial class Student { public Student() { this.Enrollments = new HashSet<Enrollment>(); } public int StudentID { get; set; } [StringLength(50)] public string LastName { get; set; } [StringLength(50)] public string FirstName { get; set; } public Nullable<System.DateTime> EnrollmentDate { get; set; } [StringLength(50)] public string MiddleName { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } }
In Enrollment.cs, add the following highlighted code.
namespace ContosoSite.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; public partial class Enrollment { public int EnrollmentID { get; set; } [Range(0, 4)] public Nullable<decimal> Grade { get; set; } public int CourseID { get; set; } public int StudentID { get; set; } public virtual Course Course { get; set; } public virtual Student Student { get; set; } } }
Build the solution.
Browse to a page for editing or creating a student. If you attempt to enter more than 50 characters, an error message is displayed.
Browse to the page for editing enrollments, and attempt to provide a grade above 4.
For a full list of data validation annotations you can apply to properties and classes, see System.ComponentModel.DataAnnotations.
Add metadata classes
Adding the validation attributes directly to the model class works when you do not expect the database to change; however, if your database changes and you need to regenerate the model class, you will lose all of the attributes you had applied to the model class. This approach can be very inefficient and prone to losing important validation rules.
To avoid this problem, you can add a metadata class that contains the attributes. When you associate the model class to the metadata class, those attributes are applied to the model. In this approach, the model class can be regenerated without losing all of the attributes that have been applied to the metadata class.
In the Models folder, add a class named Metadata.cs.
Replace the code in Metadata.cs with the following code.
using System; using System.ComponentModel.DataAnnotations; namespace ContosoSite.Models { public class StudentMetadata { [StringLength(50)] public string LastName; [StringLength(50)] public string FirstName; [StringLength(50)] public string MiddleName; } public class EnrollmentMetadata { [Range(0, 4)] public Nullable<decimal> Grade; } }
These metadata classes contain all of the validation attributes that you had previously applied to the model classes. Now, you must associate the model classes with the metadata classes.
Open Student.cs. Remove the validation attributes you had applied, and add a MetadataType attribute to the class as shown below. Provide the StudentMetadata type as a parameter to the MetadataType attribute.
namespace ContosoSite.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; [MetadataType(typeof(StudentMetadata))] public partial class Student { public Student() { this.Enrollments = new HashSet<Enrollment>(); } public int StudentID { get; set; } public string LastName { get; set; } public string FirstName { get; set; } public Nullable<System.DateTime> EnrollmentDate { get; set; } public string MiddleName { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } }
Open Enrollment.cs, and make similar changes as shown below.
namespace ContosoSite.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; [MetadataType(typeof(EnrollmentMetadata))] public partial class Enrollment { public int EnrollmentID { get; set; } public Nullable<decimal> Grade { get; set; } public int CourseID { get; set; } public int StudentID { get; set; } public virtual Course Course { get; set; } public virtual Student Student { get; set; } } }
Run the application, and notice that the validation rules are still applied.
If you need to regenerate the model class, simply reapply the MetadataType attribute to the model class to ensure that all of the validation attributes are persisted.
Conclusion
This series provided a simple example of how to generate code from an existing database that enables users to edit, update, create and delete data. It used ASP.NET MVC 5, Entity Framework and ASP.NET Scaffolding to create the project.
For an introductory example of Code First development, see Getting Started with ASP.NET MVC 5.
For a more advanced example, see Creating an Entity Framework Data Model for an ASP.NET MVC 4 App. Note that the DbContext API that you use for working with data in Database First is the same as the API you use for working with data in Code First. Even if you intend to use Database First, you can learn how to handle more complex scenarios such as reading and updating related data, handling concurrency conflicts, and so forth from a Code First tutorial. The only difference is in how the database, context class, and entity classes are created.
Comments (0) RSS Feed