TechAid24

Your Technical Consultant

Understanding Data Annotation Attributes in ASP.NET MVC for Better Validation

Posted on by Anonymous Guest 6 minutes read

Data Annotations in Entity Framework are used to define constraints, validations, and other data-related attributes directly in your C# code. They are used to configure the database schema, data types, and validation rules for your entities. Here’s a list of common Data Annotations in Entity Framework along with an example code:

 

In Data Annotations, we have two types of namespaces that have their specific in-build types.

1. System.ComponentModel.DataAnnotations incorporate the subsequent attributes that affect and check the size or nullability of the column.

2. System.ComponentModel.DataAnnotations.Schema namespace comprises the subsequent attributes that reshape the schema of the database.

 

Why and When to Use Data Annotations

Data annotations (DAs) are used to provide metadata to your code, which can help to control the behavior of your code. By using DAs in your code, you can ensure that your application is more robust, reliable, and maintainable. Here are some reasons why and when you might use data annotations:

  1. Data Validation — DAs can be used to enforce data validation rules, ensuring that data entered into your application meets certain requirements. For example, the [Required] annotation can be used to ensure that a property is not null or empty, and the [Range] annotation can be used to ensure that a numeric property falls within a specific range.
  2. Display Formatting — DAs can be used to control how data is displayed in your application’s user interface. For example, the [DisplayFormat] annotation can be used to control the formatting of a date or time property.
  3. Data Mapping — DAs can be used to specify how your entity is mapped to the database. For example, the [Key] annotation can be used to specify the primary key for your entity, and the [ForeignKey] annotation can be used to specify the foreign key for a navigation property.
  4. Model Binding — DAs can be used to control how data is bound to your application’s model. For example, the [Bind] annotation can be used to specify which properties should be included or excluded when binding to a model.
  5. Concurrency Control — DAs can be used to handle concurrency issues when updating data. For example, the [Timestamp] annotation can be used to include a timestamp property in your entity, which can be used to detect when data has been modified by another user.
System.ComponentModel.DataAnnotations Related Attributes

Here, is a list of some important Data Annotation Attributes.

1. Required: Specifies that the Input field cannot be empty. Example:
[Required(ErrorMessage = "Name is Required")]
public string Name { get; set; }
2. DisplayName: Specifies the Display Name for a Property. Example:
[DisplayName("Enter Your Name: ")]
public string Name { get; set; }
3. StringLength: Specifies minimum and maximum length for a property. Example:
[StringLength(50, MinimumLength = 3)]
public string Name { get; set; }
4. Range: Specifies a range of numeric values. Example:
[Range(1,120, ErrorMessage ="Age must be between 1-120 in years.")]
public int Age { get; set; }
5. Bind: Include or Exclude value when adding form values to model properties. Example:
[Bind(Exclude = "Id")]
6. ScaffoldColumn: Specifies a field for hiding from editor forms. Example:
[ScaffoldColumn(false)]
public int Id { get; set; }
7. DisplayFormat: Specifies a display format for a property like Date Format, Currency format etc. Example:
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy hh:mm:ss tt}")]
public System.DateTime? HireDate { get; set; }
8. ReadOnly: It set a property to read-only. Example:
[ReadOnly(true)]
public string Name { get; private set; }
9. MaxLength: Specifies max length of string. Example:
[MaxLength(50)]
public string Name { get; set; }
10. CreditCard: specifies that a data field value is credit card number. Example:
[DataType(DataType.CreditCard)]
public string Name { get; set; }
11. Compare: compare with other input fields. Example:
[System.ComponentModel.DataAnnotations.Compare("Email", ErrorMessage = "Email Not Matched")]
public string ConfirmEmail { get; set; }
12. EmailAddress: specifies that an input field value is a well-formed Email Address using Regular Expression. Example:
[Required(ErrorMessage = "Email ID is Required")]
[DataType(DataType.EmailAddress)]
[MaxLength(50)]
[RegularExpression(@ "[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Incorrect Email Format")]
public string Email { get; set;}
13. Phone: specifies that an input field value is well-formed phone number using Regular Expression. Example:
[DataType(DataType.PhoneNumber)]
[RegularExpression(@"^\(?([0-9]{2})[-. ]?([0-9]{4})[-. ]?([0-9]{3})[-. ]?([0-9]{3})$", ErrorMessage = "Not a valid Phone number")]
public string Name { get; set; }

Output format: 91-1234-567-890

14. Url: specifies URL validation. Example:
[Url][Required]
public string URL { get; set; }
15. RegularExpression: specifies that the input field is matched with the desired Regular Expression. Example:
[RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Incorrect Email Format")]
public string Email { get; set; }
16. DataType: provides a list of data type that is associated with input field and parameter. Example:
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
17. HiddenInput: specifies a hidden input field. Example:
[System.Web.Mvc.HiddenInput(DisplayValue = false)]
public string Name { get; set; }
System.ComponentModel.DataAnnotations.Schema Related Attributes

1. Table: Specifies the name of the database table associated with an entity class.

[Table("Employees")]
public class Employee
{
    // Properties...
}

2. Column:  Specifies the name and data type of a database column associated with a property.

[Column("FullName", TypeName = "nvarchar(100)")]
public string Name { get; set; }

3. Index:  Specifies an index on one or more columns of a table.

[Index("IX_FirstNameLastName", 1, IsUnique = true)]
[Index("IX_FirstNameLastName", 2, IsUnique = true)]
public string FirstName { get; set; }

[Index("IX_FirstNameLastName", 3, IsUnique = true)]
public string LastName { get; set; }

4. ForeignKey:  Specifies a foreign key relationship between entities.

public class Student
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
        
    [ForeignKey("Standard")]
    public int StandardId { get; set; }
    public Standard Standard { get; set; }
}

public class Standard
{
    public int StandardId { get; set; }
    public string StandardName { get; set; }
    
    public ICollection<Student> Students { get; set; }
}

5. NotMapped:  Excludes a property or class from being mapped to the database.

[NotMapped]
public int CalculatedValue { get; set; }

6. DatabaseGenerated: Defines how a value for a database column is generated, such as identity, computed, or none.

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int EmployeeId { get; set; }

7. InverseProperty:  Specifies the inverse navigation property in a many-to-many relationship.

public class Student
{
    public int StudentId { get; set; }
    public string Name { get; set; }

    [InverseProperty("Students")]
    public ICollection<Course> Courses { get; set; }
}

public class Course
{
    public int CourseId { get; set; }
    public string Title { get; set; }

    [InverseProperty("Courses")]
    public ICollection<Student> Students { get; set; }
}

8. ComplexType: Marks a class as a complex type, which is a class that doesn’t have a primary key and is used as part of another entity.

[ComplexType]
public class Address
{
    public string Street { get; set; }
    public string City { get; set; }
    public string State { get; set; }
}

9. DefaultValue: DefaultValue data annotation is used to specify a default value for a property.

[DefaultValue(0)]
public int Quantity { get; set; }

 

These are some of the commonly used Data Annotations in Entity Framework. You can use these attributes to define the structure, constraints, and relationships of your data model when working with Entity Framework.

Tags:

Anonymous Guest

An anonymous author is a writer who conceals their true identity when publishing content, often for privacy, security, or confidentiality reasons. This approach is often used in technical articles to focus on the information being presented rather than the author's personal identity.

Leave a Reply

Your email address will not be published. Required fields are marked *