Getting started with EF Core

Frequently used annotations

Frequently used data annotations

Below or some of the frequently used annotations in order to configure the entities the way we want

Index

You can specify an index over a column as follows:

[Index(nameof(Url))]
public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
}

Index uniqueness

You can make an index unique as follows:

[Index(nameof(Url), IsUnique = true)]
public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
}

Column names

If you prefer to configure your columns with different names, you can do so as following code snippet:

public class Blog
{
    [Column("blog_id")]
    public int BlogId { get; set; }

    public string Url { get; set; }
}

Maximum length

In the following example, configuring a maximum length of 500 will cause a column of type nvarchar(500) to be created on SQL Server:

public class Blog
{
    public int BlogId { get; set; }

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

Precision and Scale

public class Blog
{
    public int BlogId { get; set; }
    
    [Precision(14, 2)]
    public decimal Score { get; set; }
    
    [Precision(3)]
    public DateTime LastUpdated { get; set; }
}

Key

You can configure a single property to be the primary key of an entity as follows:

internal class Car
{
    [Key]
    public string LicensePlate { get; set; }

    public string Make { get; set; }
    public string Model { get; set; }
}

Last updated