How do Data Annotations work in C#?

How do Data Annotations work in C#?

Data Annotations in C# are attributes that can be applied to classes and class properties to provide metadata and validation rules. They are part of the System.ComponentModel.DataAnnotations namespace and are commonly used in data-driven applications, especially when working with ASP.NET MVC, Entity Framework, and other data access frameworks.

Data Annotations provide a declarative way to define validation rules and additional metadata for the properties of a class. These attributes can be used by various components, such as ASP.NET MVC model binding, automatic scaffolding, and data validation.

Here are some common Data Annotations and how they work:

  1. StringLengthAttribute:
    • Specifies the maximum and minimum length of a string property.
    • It helps enforce length constraints during validation.
using System.ComponentModel.DataAnnotations;

public class Person
{
    [StringLength(50, MinimumLength = 2)]
    public string Name { get; set; }
}
  1. RequiredAttribute:
    • Specifies that a property must have a non-null value.
    • It ensures that a value is provided for the property during validation.
using System.ComponentModel.DataAnnotations;

public class Employee
{
    [Required]
    public string FirstName { get; set; }

    [Required]
    public string LastName { get; set; }
}
  1. RangeAttribute:
    • Specifies a range of allowable values for numeric properties.
    • It enforces that the property value falls within the specified range during validation.
using System.ComponentModel.DataAnnotations;

public class Product
{
    [Range(0, 100)]
    public int StockQuantity { get; set; }
}
  1. RegularExpressionAttribute:
    • Specifies a regular expression pattern that a string property value must match.
    • It enforces a specific format for the property value during validation.
using System.ComponentModel.DataAnnotations;

public class Customer
{
    [RegularExpression(@"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b")]
    public string Email { get; set; }
}

Data Annotations can be used not only on individual properties but also on the class itself to provide overall metadata and validation rules for the entire class.

In ASP.NET MVC applications, Data Annotations are commonly used for model validation. During model binding, the framework automatically validates the model based on the Data Annotations applied to the properties. If any validation rules fail, the ModelState becomes invalid, and appropriate error messages can be displayed to the user.

In summary, Data Annotations in C# provide a convenient way to define validation rules and metadata for classes and properties, making data validation and model binding more straightforward and less error-prone.

Examples

  1. "C# Data Annotations Required attribute example"

    Code Implementation:

    public class Person
    {
        [Required]
        public string Name { get; set; }
    }
    

    Description: This code snippet demonstrates using the [Required] Data Annotation to mark the Name property as required for a Person class.

  2. "C# Data Annotations StringLength attribute example"

    Code Implementation:

    public class Product
    {
        [StringLength(50)]
        public string ProductName { get; set; }
    }
    

    Description: The code showcases the use of [StringLength] Data Annotation to specify a maximum length for the ProductName property in a Product class.

  3. "Data Annotations RegularExpression attribute in C#"

    Code Implementation:

    public class EmailModel
    {
        [RegularExpression(@"^\S+@\S+\.\S+$")]
        public string Email { get; set; }
    }
    

    Description: This code example utilizes the [RegularExpression] Data Annotation to enforce a regular expression pattern for the Email property in an EmailModel class.

  4. "C# Data Annotations Range attribute example"

    Code Implementation:

    public class Employee
    {
        [Range(18, 60)]
        public int Age { get; set; }
    }
    

    Description: The code demonstrates using the [Range] Data Annotation to specify a range for the Age property in an Employee class.

  5. "Data Annotations DataType attribute in C#"

    Code Implementation:

    public class Book
    {
        [DataType(DataType.Date)]
        public DateTime PublicationDate { get; set; }
    }
    

    Description: This code showcases the use of [DataType] Data Annotation to specify the data type for the PublicationDate property in a Book class.

  6. "C# Data Annotations Display attribute example"

    Code Implementation:

    public class Product
    {
        [Display(Name = "Product Title")]
        public string Title { get; set; }
    }
    

    Description: The code illustrates the [Display] Data Annotation to customize the display name for the Title property in a Product class.

  7. "Data Annotations Key attribute in C#"

    Code Implementation:

    public class Student
    {
        [Key]
        public int StudentId { get; set; }
    }
    

    Description: This code demonstrates the use of [Key] Data Annotation to specify that StudentId is the primary key for a Student class.

  8. "C# Data Annotations Compare attribute example"

    Code Implementation:

    public class PasswordModel
    {
        [Compare("ConfirmPassword")]
        public string Password { get; set; }
    
        public string ConfirmPassword { get; set; }
    }
    

    Description: The code utilizes the [Compare] Data Annotation to ensure that the Password property matches the ConfirmPassword property in a PasswordModel class.

  9. "Data Annotations CustomValidation attribute in C#"

    Code Implementation:

    public class CustomModel
    {
        [CustomValidation(typeof(CustomModelValidator), "ValidateCustomProperty")]
        public string CustomProperty { get; set; }
    }
    
    public class CustomModelValidator
    {
        public static ValidationResult ValidateCustomProperty(string value, ValidationContext context)
        {
            // Custom validation logic
            // ...
            return ValidationResult.Success;
        }
    }
    

    Description: This code demonstrates using the [CustomValidation] Data Annotation along with a custom validator class (CustomModelValidator) to perform custom validation for the CustomProperty in a CustomModel class.


More Tags

google-api-nodejs-client web-scraping attributes stack-trace procfs chrome-ios logfile stream proc uitableview

More C# Questions

More Electrochemistry Calculators

More Biology Calculators

More Mortgage and Real Estate Calculators

More Various Measurements Units Calculators