索引鍵 (主要)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 應用程式開發介面Fluent API

您可以使用 fluent 應用程式開發的應用程式開發介面來設定單一屬性是實體的索引鍵。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 應用程式開發的應用程式開發介面來設定多個屬性作為索引鍵的實體 (稱為複合索引鍵)。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; }
}