Data Annotations

Use data annotations to configure a model

You can also apply certain attributes (known as Data Annotations) to your classes and properties.

Data annotations will override conventions but will be overridden by Fluent API configuration.

(Remember: Fluent API > Annotations > Conventions)

Data Annotation examples

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;

[Table("Blogs")]
public class Blog
{
    public int BlogId { get; set; }

    [Required]
    public string Url { get; set; }
}

Note the following here

  • we need a couple of name spaces in order to use data notations as shown in line 1 and 2

  • line 5 maps the Blog entity to Blogs table

  • line 10 marks the Url property as required

We can also use two annotations together on a single property, if required by business rules!

Last updated