What is DataAnnotations in MVC?

Posted by  Joseph Rossignol
 581  View(s)
Ratings:
Rate this:

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

  1. Re: What is DataAnnotations in MVC?

    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.

Answer