What is DataAnnotations in MVC?

Please describe what is DataAnnotations in MVC with example and describe all attributes of it.

Last updated:2/12/2020 3:33:58 AM

2 Answers

Nishi Tiwari
Nishi Tiwari

The DataAnnotations are used to configure our model classes, which will highlight the most commonly needed configurations and also DataAnnotations are understood by a number of .NET applications, such as ASP.NET MVC, which allows those applications to leverage the same annotations for client-side validations. The DataAnnotation attributes override default Code-First conventions.

The System.ComponentModel.DataAnnotations includes the following attributes which mainly impacts the nullability or size of the column.

  •  Key
  •  Timestamp
  •  ConcurrencyCheck 
  •  Required
  •  MinLength
  •  MaxLength
  •  StringLength

Key

The Entity Framework mainly relies on entities having a key-value which it uses for tracking entities. The conventions that Code First depends on how it implies which property is the key in each of the Code First classes.

We can use the key annotation to specify which property is to be used as the EntityKey.

Now let’s take a look at the Student class which contains StdntID and it doesn’t follow the default Code First convention so to handle this, the key attribute is added, which will make it a primary key.

public class Student{

   [Key]
   public int StdntID { get; set; }
   public string LastName { get; set; }
   public string FirstMidName { get; set; }
   public DateTime EnrollmentDate { get; set; }

   public virtual ICollection<Enrollment> Enrollments { get; set; }
}

When we run the application and look into the database in SQL Server Explorer, we will see that the primary key is now StdntID in the Students table.

What is DataAnnotations in MVC?

The Entity Framework also supports composite keys and Composite keys are primary keys that consist of more than one property.

public class DrivingLicense{

   [Key, Column(Order = 1)]
   public int LicenseNumber { get; set; }

   [Key, Column(Order = 2)]
   public string IssuingCountry { get; set; }
   public DateTime Issued { get; set; }
   public DateTime Expires { get; set; }
}

When we have composite keys, Entity Framework requires us to define an order of the key properties.

Timestamp

The Code First will treat Timestamp properties the same as ConcurrencyCheck properties, but it also ensures that the database field generated by Code First is non-nullable.

So, it is more common to use row version or timestamp fields for concurrency checking and rather than using the ConcurrencyCheck annotation, we can use the more specific TimeStamp annotation as long as the type of the property is a byte array. We can only have one timestamp property in a given class.

Now take a look at a simple example by adding the TimeStamp property to the Course class.

public class Course{

   public int CourseID { get; set; }
   public string Title { get; set; }
   public int Credits { get; set; }
   [Timestamp]
   public byte[] TStamp { get; set; }

   public virtual ICollection<Enrollment> Enrollments { get; set; }
}

ConcurrencyCheck

This ConcurrencyCheck annotation allows us to flag one or more properties to be used for concurrency checking in the database when a user edits or deletes an entity and if they were working with the EF Designer, this aligns with setting a property's ConcurrencyMode to Fixed.

Now take a look at a simple example and see how ConcurrencyCheck works by adding it to the Title property in Course class.

public class Course{

   public int CourseID { get; set; }

   [ConcurrencyCheck]
   public string Title { get; set; }
   public int Credits { get; set; }

   [Timestamp, DataType("timestamp")]
   public byte[] TimeStamp { get; set; }

   public virtual ICollection<Enrollment> Enrollments { get; set; }
}

Required

This Required annotation tells EF that a particular property is required and now have a look at the following Student class in which Required id is added to the FirstMidName property. The Required attribute will force EF to ensure that the property has data in it.

public class Student{

   [Key]
   public int StdntID { get; set; }

   [Required]
   public string LastName { get; set; }

   [Required]
   public string FirstMidName { get; set; }
   public DateTime EnrollmentDate { get; set; }

   public virtual ICollection<Enrollment> Enrollments { get; set; }
}

We can see in the above example of Student class Required attribute is applied to FirstMidName and LastName. The Code First will create a NOT NULL FirstMidName and LastName column in the Students table.

What is DataAnnotations in MVC?

MaxLength

This MaxLength attribute allows us to specify additional property validations so it can be applied to a string or array type property of a domain class. The EF Code First will set the size of a column as specified in the MaxLength attribute.

public class Course{

   public int CourseID { get; set; }
   [ConcurrencyCheck]
   [MaxLength(24)]

   public string Title { get; set; }
   public int Credits { get; set; }

   public virtual ICollection<Enrollment> Enrollments { get; set; }
}

When we run the above application, Code-First will create a nvarchar(24) column Title in the Coursed table

What is DataAnnotations in MVC?

And now when the user sets the Title which contains more than 24 characters, EF will throw EntityValidationError.

MinLength

This MinLength attribute allows us to specify additional property validations, just as we did with MaxLength. The MinLength attribute can also be used with the MaxLength attribute.

public class Course{

   public int CourseID { get; set; }
   [ConcurrencyCheck]
   [MaxLength(24) , MinLength(5)]
   public string Title { get; set; }
   public int Credits { get; set; }

   public virtual ICollection<Enrollment> Enrollments { get; set; }
}

The EF will throw EntityValidationError if we set a value of Title property less than the specified length in MinLength attribute or greater than the specified length in the MaxLength attribute.

StringLength

The StringLength also allows us to specify additional property validations like MaxLength and the difference being StringLength attribute can only be applied to a string type property of Domain classes.

public class Course{

   public int CourseID { get; set; }
   [StringLength (24)]
   public string Title { get; set; }
   public int Credits { get; set; }

   public virtual ICollection<Enrollment> Enrollments { get; set; }
}

The Entity Framework also validates the value of a property for the StringLength attribute and also if the user sets the Title, which contains more than 24 characters, then EF will throw EntityValidationError.

Shrikant Mishra
Shrikant Mishra

Into the ASP.NET MVC uses DataAnnotations attributes to implement validations. The DataAnnotations includes built-in validation attributes for different validation rules, which can be applied to the properties of the model class. The DotNet MVC framework will automatically enforce these validation rules and display validation messages in the view.

The DataAnnotations attributes included in System.ComponentModel.DataAnnotations namespace. The following table lists DataAnnotations validation attributes.

Attribute

Description

Required
Indicates that the property is a required field
StringLength
Defines a maximum length for string field
Range
Defines a maximum and minimum value for a numeric field
RegularExpression
Specifies that the field value must match with specified Regular Expression
CreditCard
Specifies that the specified field is a credit card number
CustomValidation
Specified custom validation method to validate the field
EmailAddress
Validates with the email address format
FileExtension
Validates with the file extension
MaxLength
Specifies maximum length for a string field
MinLength
Specifies minimum length for a string field
Phone Specifies that a field is a phone number using regular expression for phone numbers

Answer