EF Core and C# Model Validation



Data validation with Entity Framework Core and C# data models can be fun. In this tutorial, you will learn about some of the most useful annotation attributes that can be used to provide validation for a C# model.

To use data validation attributes, you will use the DataAnnotations namespace.

using System.ComponentModel.DataAnnotations;

Common Attributes: Key and Required

Among the most common data validation annotations are the Key and Required keywords. When using a code-first design, EF Core will attempt to choose a unique key when storing an entity in the database. For example, if ID or classnameID appears in the model, it will be automatically identified as the key. However, if you do not wish to use these naming conventions, you can designate a property as the entity's key by using the Key annotation.

public int UniqueIdentifier { get; set; }

Next, suppose there are properties for which you insist values be stored in the Entity Framework database. You can designate a property as a required property using the Required keyword annotation.

public string Name { get; set; }

Now, when you attempt to bind to this model property from a form input, on an ASP.NET web frontend for instance, data validation will automatically take place and an error will display if the user leaves the field blank.

Working with Strings

Suppose you want to ensure that the string entered for the Name field does not exceed a specified number of characters. You can add string length limit validation using the StringLength annotation.

public string Name { get; set; }

You can also set a minimum length for a string. The following annotation will validate that a given string is between 3 characters and 50 characters.

[StringLength(50,MinimumLength = 3)]

Note, you can combine multiple data annotations. For example, to define the Name property as required, simply stack the Required and StringLength annotations.

public string Name { get; set; }

Validating Specific Data Types

Data annotations can be used to provide simple validation for specific data types. This will save you time, and allow you to focus on getting your product to market. You can, for example, annotate properties that represent credit card numbers, phone numbers, email addresses, and URLs.

To validate that a property is formatted as a credit card number, use the [CreditCard] data annotation. To perform preliminary data validation for a phone number property in a C# data model, use the [Phone] annotation. To validate an email address, annotate the property using the [EmailAddress] keyword. Finally, to ensure that an EF Core property's value is a URL, use the [Url] data annotation. Consider the following example.

public string CreditCardNumber { get; set; }
public string PhoneNumber { get; set; }
public string EmailAddress { get; set; }
public string Website { get; set; }

Working with Numbers

If you are working with numbers in your data model, you may need to set some guidelines. For example, you may only want to accept positive integers, or values that fall between a given range. Setting a range of valid values is as simple as using the Range(min, max) syntax as a data annotation.

public int Percentage { get; set; }

Now, only values between 0 and 100 will be accepted as valid for the Percentage property. In this case, the values must also be integer values since the data type is int.

Custom Error Messages

Suppose you are using the following annotated property in your data model.

public string LastName1 { get; set; }

If the end user attempts to leave the field blank, they will receive an error message that the LastName1 field is required. Using the property's name in the error message, in this case, does not produce a very user-friendly message. If you would rather the error say "The Last Name field is required," you are in luck. You can use DataAnnotations to set the name of the property to be used in validation messages using the Display keyword.

[Display(Name = "Last Name")]
public string LastName1 { get; set; }

Instead of using the default validation error messages for such field annotations as Range and StringLength, you can define custom error messages as an attribute of the annotation.

[StringLength(50, ErrorMessage = "Name must be fewer than 50 characters.")]

The Bottom Line

In this tutorial, you learned how a code-first design approach can be used to easily add data validation to a C# data model. Using the validation annotations found in the System.ComponentModel.DataAnnotations namespace will automatically validate strings and numbers before storing them in the database. It even provides a way to give custom error messages on the frontend in case a value is not valid. These techniques help ensure only valid values are store in your Entity Framework Core database.

Don't stop learning!

There is so much to discover about C#. That's why I am making my favorite tips and tricks available for free. Enter your email address below to become a better .NET developer.

Did you know?

Our beautiful, multi-column C# reference guides contain more than 150 tips and examples to make it even easier to write better code.

Get your cheat sheets