"
 
 
 
ASP.NET (snapshot 2017) Microsoft documentation and samples

EF Database First with ASP.NET MVC: Enhancing Data Validation

by Tom FitzMacken

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 and display formatting. It was improved based on feedback from users in the comments section.

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. You can also apply formatting attributes that change how the properties are displayed; such as, changing the value used for text labels.

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.

[!code-csharpMain]

   1:  namespace ContosoSite.Models
   2:  {
   3:      using System;
   4:      using System.Collections.Generic;
   5:      using System.ComponentModel.DataAnnotations;
   6:      
   7:      public partial class Student
   8:      {
   9:          public Student()
  10:          {
  11:              this.Enrollments = new HashSet<Enrollment>();
  12:          }
  13:      
  14:          public int StudentID { get; set; }
  15:          [StringLength(50)]
  16:          public string LastName { get; set; }
  17:          [StringLength(50)]
  18:          public string FirstName { get; set; }
  19:          public Nullable<System.DateTime> EnrollmentDate { get; set; }
  20:          [StringLength(50)]
  21:          public string MiddleName { get; set; }
  22:      
  23:          public virtual ICollection<Enrollment> Enrollments { get; set; }
  24:      }
  25:  }

In Enrollment.cs, add the following highlighted code.

[!code-csharpMain]

   1:  namespace ContosoSite.Models
   2:  {
   3:      using System;
   4:      using System.Collections.Generic;
   5:      using System.ComponentModel.DataAnnotations;
   6:      
   7:      public partial class Enrollment
   8:      {
   9:          public int EnrollmentID { get; set; }
  10:          [Range(0, 4)]
  11:          public Nullable<decimal> Grade { get; set; }
  12:          public int CourseID { get; set; }
  13:          public int StudentID { get; set; }
  14:      
  15:          public virtual Course Course { get; set; }
  16:          public virtual Student Student { get; set; }
  17:      }
  18:  }

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.

show error message
show error message

Browse to the page for editing enrollments, and attempt to provide a grade above 4.

grade range error
grade range error

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.

add metadata class
add metadata class

Replace the code in Metadata.cs with the following code.

[!code-csharpMain]

   1:  using System;
   2:  using System.ComponentModel.DataAnnotations;
   3:   
   4:  namespace ContosoSite.Models
   5:  {
   6:      public class StudentMetadata
   7:      {
   8:          [StringLength(50)]
   9:          [Display(Name="Last Name")]
  10:          public string LastName;
  11:   
  12:          [StringLength(50)]
  13:          [Display(Name="First Name")]
  14:          public string FirstName;
  15:   
  16:          [StringLength(50)]
  17:          [Display(Name="Middle Name")]
  18:          public string MiddleName;
  19:   
  20:          [Display(Name = "Enrollment Date")]
  21:          public Nullable<System.DateTime> EnrollmentDate;
  22:      }
  23:   
  24:      public class EnrollmentMetadata
  25:      {
  26:          [Range(0, 4)]
  27:          public Nullable<decimal> Grade;
  28:      }
  29:  }

These metadata classes contain all of the validation attributes that you had previously applied to the model classes. The Display attribute is used to change the value used for text labels.

Now, you must associate the model classes with the metadata classes.

In the Models folder, add a class named PartialClasses.cs.

Replace the contents of the file with the following code.

[!code-csharpMain]

   1:  using System;
   2:  using System.ComponentModel.DataAnnotations;
   3:   
   4:  namespace ContosoSite.Models
   5:  {
   6:      [MetadataType(typeof(StudentMetadata))]
   7:      public partial class Student
   8:      {
   9:      }
  10:   
  11:      [MetadataType(typeof(EnrollmentMetadata))]
  12:      public partial class Enrollment
  13:      {
  14:      }
  15:  }

Notice that each class is marked as a partial class, and each matches the name and namespace as the class that is automatically generated. By applying the metadata attribute to the partial class, you ensure that the data validation attributes will be applied to the automatically-generated class. These attributes will not be lost when you regenerate the model classes because the metadata attribute is applied in partial classes that are not regenerated.

To regenerate the automatically-generated classes, open the ContosoModel.edmx file. Once again, right-click on the design surface and select Update Model from Database. Even though you have not changed the database, this process will regenerate the classes. In the Refresh tab, select Tables and Finish.

refresh tables
refresh tables

Save the ContosoModel.edmx file to apply the changes.

Open the Student.cs file or the Enrollment.cs file, and notice that the data validation attributes you applied earlier are no longer in the file. However, run the application, and notice that the validation rules are still applied when you enter data.

Previous Next





Comments ( )
<00>  <01>  <02>  <03>  <04>  <05>  <06>  <07>  <08>  <09>  <10>  <11>  <12>  <13>  <14>  <15>  <16>  <17>  <18>  <19>  <20>  <21>  <22>  <23
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/mvc/overview/getting-started/database-first-development/enhancing-data-validation.htm
<SITEMAP>  <MVC>  <ASP>  <NET>  <DATA>  <KIOSK>  <FLEX>  <SQL>  <NOTES>  <LINUX>  <MONO>  <FREEWARE>  <DOCS>  <ENG>  <CHAT ME>  <ABOUT ME>  < THANKS ME>