Data Annotations in .NET

Introduction

Data annotation is critical in modern software development for guaranteeing data integrity, readability, and clarity. Data annotations in .NET provide a standardized mechanism to transmit metadata about data objects, improving the robustness and maintainability of your code. In this article, we'll look at 25 data annotations in.NET, complete with descriptions and examples.

What are Data Annotations?

In .NET, data annotations enable developers to add metadata to data models and properties. These annotations aid in the expression of constraints, formatting, and validation rules, making it easier to work with data objects in a variety of settings, such as ASP.NET applications, Entity Framework, and API validation.

1. `[Required]`

The [Required] annotation ensures that a property cannot be null.

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

2. `[StringLength]`

Defines the maximum and minimum length of a string property.

public class Product
{
    [StringLength(50, MinimumLength = 3)]
    public string Name { get; set; }
}

3. `[Range]`

Restricts a property to a specified numeric range.

public class Temperature
{
    [Range(-40, 100)]
    public int Celsius { get; set; }
}

4. `[RegularExpression]`

Validates a property against a regular expression pattern.

public class Email
{
    [RegularExpression(@"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$")]
    public string Address { get; set; }
}

5. `[Compare]`

Compares the values of two properties for equality.

public class User
{
    public string Password { get; set; }

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

6. `[EmailAddress]`

Ensures that a string property contains a valid email address.

public class Contact
{
    [EmailAddress]
    public string Email { get; set; }
}

7. `[Phone]`

Validates a string property as a phone number.

public class Contact
{
    [Phone]
    public string PhoneNumber { get; set; }
}

8. `[Url]`

Check if a string property contains a valid URL.

public class Website
{
    [Url]
    public string URL { get; set; }
}

9. `[CreditCard]`

Ensures a string property contains a valid credit card number.

public class Payment
{
    [CreditCard]
    public string CardNumber { get; set; }
}

10. `[MaxLength]`

Specifies the maximum length of a string property.

public class Tweet
{
    [MaxLength(280)]
    public string Text { get; set; }
}

11. `[MinLength]`

Sets the minimum length for a string property.

public class Password
{
    [MinLength(8)]
    public string Value { get; set; }
}

12. `[DataType]`

Specifies the data type of a property.

public class Person
{
    [DataType(DataType.Date)]
    public DateTime BirthDate { get; set; }
}

13. `[Display]`

Customizes the display name for a property.

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

14. `[ScaffoldColumn]`

Hides a property from a scaffolding in ASP.NET MVC.

public class Employee
{
    [ScaffoldColumn(false)]
    public int EmployeeID { get; set; }
}

15. `[ScaffoldTable]`

Specifies the table name for an Entity Framework Entity.

[ScaffoldTable("tbl_Product")]
public class Product
{
    public string Name { get; set; }
}

16. `[Editable]`

Determines whether a property is editable in MVC.

[Editable(false)]
public class UserProfile
{
    public string FirstName { get; set; }
}

17. `[Key]`

Marks a property as the primary key for an Entity Framework Entity.

public class Customer
{
    [Key]
    public int CustomerID { get; set; }
}

18. `[ForeignKey]`

Defines a foreign key relationship in Entity Framework.

public class Order
{
    public int CustomerID { get; set; }

    [ForeignKey("CustomerID")]
    public Customer Customer { get; set; }
}

19. `[Table]`

Specifies the table name for an Entity Framework entity.

[Table("Orders")]
public class Order
{
    public string OrderName { get; set; }
}

20. `[Column]`

Defines the column name for a property in Entity Framework.

public class User
{
    [Column("Full_Name")]
    public string FullName { get; set; }
}

21. `[ConcurrencyCheck]`

Indicates that a property should be included in optimistic concurrency checks.

public class Product
{
    [ConcurrencyCheck]
    public int UnitsInStock { get; set; }
}

22. `[Timestamp]`

Specifies that a property represents a database-generated timestamp.

public class Product
{
    [Timestamp]
    public byte[] RowVersion { get; set; }
}

23. `[DatabaseGenerated]`

Marks a property as database-generated.

public class Order
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int OrderID { get; set; }
}

24. `[NotMapped]`

Excludes a property from being mapped to the database.

public class User
{
    [NotMapped]
    public string FullName => $"{FirstName} {LastName}";
}

25. `[Bind]`

Specifies which properties should be included when binding data in an MVC action.

[Bind(Include = "FirstName, LastName, Email")]
public class UserProfile
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
}

Conclusion

Data annotations in.NET make it simple for developers to declare metadata and limitations for data models. You can improve the dependability and readability of your code by correctly applying these annotations. These annotations are useful tools in your development toolset, whether you're building online apps with ASP.NET or working with databases in Entity Framework.


Similar Articles