EF Core
Getting started with EF Core
Getting started with EF Core
  • Introduction
    • What is an ORM
    • Entity Framework Core
    • EF Core architecture
    • EF Core Approaches
  • Basics of EF Core
    • Create the project
      • Create the model & context
    • Create migration
    • CRUD using EF
      • Creating many entities
      • Update & Delete
    • Adding a property
      • Add migration
  • Entity Relationships
    • Add related entity
      • Add Vehicle
      • Modify Student
      • Modify context
      • Add migration
    • Manipulate related data
  • Entity Configuration
    • Fluent APIs
      • Frequently used APIs
    • Data Annotations
      • Frequently used annotations
Powered by GitBook
On this page
  • Frequently used data annotations
  • Index
  • Index uniqueness
  • Column names
  • Maximum length
  • Precision and Scale
  • Key
  1. Entity Configuration
  2. Data Annotations

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; }
}
PreviousData Annotations

Last updated 2 years ago