20 Must-Know Data Annotations for ASP.NET Core: Simplifying Data Management

Data annotations in ASP.NET Core are attributes that can be applied to model properties to define validation rules, format strings, and other metadata. They are a key feature of the .NET framework and can help make your code more efficient, easier to m…


This content originally appeared on Level Up Coding - Medium and was authored by Onur Derman

Data annotations in ASP.NET Core are attributes that can be applied to model properties to define validation rules, format strings, and other metadata. They are a key feature of the .NET framework and can help make your code more efficient, easier to maintain, and more secure. In this article, we will discuss 20 of the most important data annotations in ASP.NET Core, along with detailed explanations and code examples.

Important Note:
In this article I will demonstrate 20 important data annotations, first with independent examples and then at the end of the article you can find one sample entity class — Employee — in which I implement all the data annotations in the same class. Have a nice reading :)

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.

After a quick brief, let’s jump into each one of them separately in independent examples.

1- Required

The Required data annotation is used to mark a property as required. This means that the property cannot be null or empty. If the property is not set, a validation error will be raised.

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

2- Range

The Range data annotation is used to define a range for numeric properties. You can specify the minimum and maximum values for the property.

public class Product 
{
[Range(0, 100)]
public int Quantity { get; set; }
}

3- StringLength

The StringLength data annotation is used to define the maximum length of a string property.

public class Customer 
{
[StringLength(50)]
public string Name { get; set; }
}

4- RegularExpression

The RegularExpression data annotation is used to validate a property against a regular expression pattern. It is used to apply a regular expression pattern to a string property in an ASP.NET Core model class. In this case, the regular expression pattern specifies that the string must consist only of alphanumeric characters (letters and digits).

public class Account 
{
[RegularExpression(@"^[a-zA-Z0-9]*$")]
public string Username { get; set; }
}

5- EmailAddress

The EmailAddress data annotation is used to validate an email address. You can use it to ensure that the email address entered by the user is in a valid format:

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

6- CreditCard

The CreditCard data annotation is used to validate a credit card number. You can use it to ensure that the credit card number entered by the user is in a valid format:

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

7- DataType

The DataType data annotation is used to specify the data type of a property.

public class Employee 
{
[DataType(DataType.DateTime)]
public DateTime DateOfBirth { get; set; }
}

In this example I used DataType.DateTime but there are other data types that can be specified using the [DataType] attribute in ASP.NET Core. Here are some of the most commonly used ones:

DataType.Date, DataType.Time, DataType.Duration, DataType.Password, DataType.MultilineText, DataType.Password, DataType.PhoneNumber, DataType.Url, DataType.Currency …

8- Display

The Display data annotation is used to set the display name for a property in an ASP.NET Core model class. It’s used to specify the name of the property that should be displayed in user interfaces instead of the property name itself.

In the example below, it indicates that the property should be displayed as “Product Name” in user interfaces, instead of “Name”.

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

9- DisplayFormat

The DisplayFormat data annotation is used to specify the format of a property for display purposes. For example, if the property value is 100.50, it will be displayed as "$1,000.50" if the current culture uses the dollar sign as the currency symbol.

public class Order 
{
[DisplayFormat(DataFormatString = "{0:C}")]
public decimal Total { get; set; }
}

10- Compare

The Compare data annotation is used to compare two properties. We generally use it to confirm the passwords in register pages.

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

11- Remote

The Remote data annotation is used to perform remote validation of a property. This can be useful for validating uniqueness, for example.

public class Product 
{
[Remote(action: "CheckUnique", controller: "Product")]
public string Name { get; set; }
}

12- ScaffoldColumn

The ScaffoldColumn data annotation is used to specify whether a property should be included in the scaffolded views. If you have a scaffold page that lists the products, the Id property will be excluded in the List View Page.

public class Product 
{
[ScaffoldColumn(false)]
public int Id { get; set; }
}

13- ForeignKey

The ForeignKey data annotation is used to specify a foreign key relationship.

public class Order 
{
[ForeignKey("CustomerId")]
public int CustomerId { get; set; }
public Customer Customer { get; set; }
}

14- DisplayColumn

The DisplayColumn data annotation is used to specify the default column to use for display purposes.

[DisplayColumn("FullName")]
public class Person {
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName => $"{FirstName} {LastName}";
}

By setting the [DisplayColumn(“FullName”)] attribute, you are telling ASP.NET Core to use the FullName property as the default column to display when scaffolding views for the Person model class.

15- Bind

The Bind data annotation is used to specify which properties of a model should be included in model binding.

In this example only Firstname, LastName and Email properties will be passed to the Create method inside customer parameter.

public IActionResult Create([Bind("FirstName, LastName, Email")] Customer customer) 
{
// ...
}

16- HiddenInput

The HiddenInput data annotation is used to specify that a property should be rendered as a hidden input field.

public class Order 
{
[HiddenInput]
public int Id { get; set; }
}

In the code you provided, the Order class has an Id property decorated with the [HiddenInput] attribute, which means that it will not be displayed in any form generated by ASP.NET Core.

17- DisplayOrder

The DisplayOrder data annotation is used to specify the order in which properties should be displayed.

public class Product 
{
[DisplayOrder(1)]
public int Id { get; set; }
[DisplayOrder(2)]
public string Name { get; set; }
}

18- Timestamp

The Timestamp data annotation is used to specify that a property should be used for optimistic concurrency checking.

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

[Timestamp]
public byte[] Timestamp { get; set; }

public string CustomerName { get; set; }
public decimal TotalAmount { get; set; }
}

In this example, the Timestamp property is decorated with the [Timestamp] attribute. This tells ASP.NET Core to use this property to perform optimistic concurrency checks when updating records in the database.

Optimistic concurrency is a technique used to prevent two users from updating the same record at the same time and overwriting each other’s changes. When you perform an update operation on a record with a timestamp property, ASP.NET Core will compare the timestamp value of the record in the database with the timestamp value that you provide in your update operation. If the values match, the update is allowed to proceed. If the values do not match, it means that another user has updated the record since you retrieved it, and your update will be rejected.

By using the [Timestamp] attribute, you can enable optimistic concurrency checks in your ASP.NET Core model classes and ensure that your data stays consistent even in a multi-user environment.

19- DefaultValue

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

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

20- NotMapped

The NotMapped data annotation is used to specify that a property should not be mapped to a database column.

public class Product 
{
[NotMapped]
public string FullName => $"{Name} ({Brand})";
}

Now let’s look at the Employee entity class and see that can we implement a significant number of data annotation for just one entity class.

Note: There are additional data annotations below that does not exist above.

Here is the Employee class:

public class Employee
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

[Required(ErrorMessage = "First name is required")]
[StringLength(50)]
public string FirstName { get; set; }

[Required(ErrorMessage = "Last name is required")]
[StringLength(50)]
public string LastName { get; set; }

[DataType(DataType.EmailAddress)]
[EmailAddress(ErrorMessage = "Invalid email address")]
public string Email { get; set; }

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime Birthdate { get; set; }

[Range(0, 10, ErrorMessage = "Rating must be between 0 and 10")]
public int Rating { get; set; }

[RegularExpression("^[0-9]{10}$", ErrorMessage = "Phone number must be 10 digits")]
public string PhoneNumber { get; set; }

[CreditCard(ErrorMessage = "Invalid credit card number")]
public string CreditCardNumber { get; set; }

[Url(ErrorMessage = "Invalid website URL")]
public string Website { get; set; }

[MaxLength(500)]
public string Bio { get; set; }

[MinLength(6, ErrorMessage = "Password must be at least 6 characters long")]
[DataType(DataType.Password)]
public string Password { get; set; }

[Compare("Password", ErrorMessage = "Passwords do not match")]
[DataType(DataType.Password)]
public string ConfirmPassword { get; set; }

[ForeignKey("Department")]
public int DepartmentId { get; set; }
public Department Department { get; set; }

[DisplayColumn("FullName")]
public string FullName => $"{FirstName} {LastName}";

[Bind("FirstName, LastName, Email")]
public void UpdateEmployee(Employee newEmployee)
{
FirstName = newEmployee.FirstName;
LastName = newEmployee.LastName;
Email = newEmployee.Email;
}

[HiddenInput]
public int SecretCode { get; set; }

[DisplayOrder(1)]
public int EmployeeNumber { get; set; }

[Timestamp]
public byte[] Timestamp { get; set; }

[DefaultValue(10000)]
public decimal Salary { get; set; }

[NotMapped]
public string FullNameAndDepartment => $"{FullName} ({Department.Name})";
}

In conclusion

Data annotations are a powerful feature of ASP.NET Core that can help you write cleaner, more efficient, and more secure code. By using these annotations to define validation rules, format strings, and other metadata for your model properties, you can simplify your code and make it easier to maintain. By understanding and using the 20 most important data annotations listed above, you can take full advantage of this feature and build better ASP.NET Core applications.

I appreciate your participation and hope that my article has provided you with valuable insights. Thank you for taking the time to read it thus far.


20 Must-Know Data Annotations for ASP.NET Core: Simplifying Data Management was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Onur Derman


Print Share Comment Cite Upload Translate Updates
APA

Onur Derman | Sciencx (2023-05-14T15:10:05+00:00) 20 Must-Know Data Annotations for ASP.NET Core: Simplifying Data Management. Retrieved from https://www.scien.cx/2023/05/14/20-must-know-data-annotations-for-asp-net-core-simplifying-data-management/

MLA
" » 20 Must-Know Data Annotations for ASP.NET Core: Simplifying Data Management." Onur Derman | Sciencx - Sunday May 14, 2023, https://www.scien.cx/2023/05/14/20-must-know-data-annotations-for-asp-net-core-simplifying-data-management/
HARVARD
Onur Derman | Sciencx Sunday May 14, 2023 » 20 Must-Know Data Annotations for ASP.NET Core: Simplifying Data Management., viewed ,<https://www.scien.cx/2023/05/14/20-must-know-data-annotations-for-asp-net-core-simplifying-data-management/>
VANCOUVER
Onur Derman | Sciencx - » 20 Must-Know Data Annotations for ASP.NET Core: Simplifying Data Management. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2023/05/14/20-must-know-data-annotations-for-asp-net-core-simplifying-data-management/
CHICAGO
" » 20 Must-Know Data Annotations for ASP.NET Core: Simplifying Data Management." Onur Derman | Sciencx - Accessed . https://www.scien.cx/2023/05/14/20-must-know-data-annotations-for-asp-net-core-simplifying-data-management/
IEEE
" » 20 Must-Know Data Annotations for ASP.NET Core: Simplifying Data Management." Onur Derman | Sciencx [Online]. Available: https://www.scien.cx/2023/05/14/20-must-know-data-annotations-for-asp-net-core-simplifying-data-management/. [Accessed: ]
rf:citation
» 20 Must-Know Data Annotations for ASP.NET Core: Simplifying Data Management | Onur Derman | Sciencx | https://www.scien.cx/2023/05/14/20-must-know-data-annotations-for-asp-net-core-simplifying-data-management/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.