Keys (primary)

A key serves as the primary unique identifier for each entity instance. When using a relational database this maps to the concept of a primary key. You can also configure a unique identifier that is not the primary key (see Alternate Keys for more information).

One of the following methods can be used to setup/create a primary key.

Conventions

By convention, a property named Id or <type name>Id will be configured as the key of an entity.

class Car
{
    public string Id { get; set; }

    public string Make { get; set; }
    public string Model { get; set; }
}
class Car
{
    public string CarId { get; set; }

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

Data Annotations

You can use Data Annotations to configure a single property to be the key of an entity.

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

namespace EFModeling.Configuring.DataAnnotations.Samples.KeySingle
{
    class MyContext : DbContext
    {
        public DbSet<Car> Cars { get; set; }
    }

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

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

Fluent API

You can use the Fluent API to configure a single property to be the key of an entity.

using Microsoft.EntityFrameworkCore;

namespace EFModeling.Configuring.FluentAPI.Samples.KeySingle
{
    class MyContext : DbContext
    {
        public DbSet<Car> Cars { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Car>()
                .HasKey(c => c.LicensePlate);
        }
    }

    class Car
    {
        public string LicensePlate { get; set; }

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

You can also use the Fluent API to configure multiple properties to be the key of an entity (known as a composite key). Composite keys can only be configured using the Fluent API - conventions will never setup a composite key and you can not use Data Annotations to configure one.

using Microsoft.EntityFrameworkCore;

namespace EFModeling.Configuring.FluentAPI.Samples.KeyComposite
{
    class MyContext : DbContext
    {
        public DbSet<Car> Cars { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Car>()
                .HasKey(c => new { c.State, c.LicensePlate });
        }
    }

    class Car
    {
        public string State { get; set; }
        public string LicensePlate { get; set; }

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