索引鍵 (主要)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).

慣例Conventions

依照慣例,屬性名為Id<type name>Id會設定為實體的索引鍵。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.

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

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

Fluent APIFluent API

您可以使用 Fluent API 來設定實體的索引鍵的單一屬性。You can use the Fluent API to configure a single property to be the key of an entity.

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

您也可以使用 Fluent API 來設定多個屬性 (又稱為複合索引鍵) 的實體索引鍵。You can also use the Fluent API to configure multiple properties to be the key of an entity (known as a composite key). 複合索引鍵可以只設定使用 Fluent API-慣例永遠不會設定複合索引鍵而且您可以使用資料註解來設定其中一個。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.

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