主索引鍵Primary Keys

注意

本節中的設定是一般適用於關聯式資料庫。The configuration in this section is applicable to relational databases in general. 當您安裝的關聯式資料庫提供者,如下所示的擴充方法會變成可用 (因為共用Microsoft.EntityFrameworkCore.Relational封裝)。The extension methods shown here will become available when you install a relational database provider (due to the shared Microsoft.EntityFrameworkCore.Relational package).

針對每個實體類型的索引鍵引進主索引鍵條件約束。A primary key constraint is introduced for the key of each entity type.

慣例Conventions

依照慣例,在資料庫中的主索引鍵將名為PK_<type name>By convention, the primary key in the database will be named PK_<type name>.

資料註釋Data Annotations

使用資料註解可以不設定任何關聯式資料庫的特定層面的主索引鍵。No relational database specific aspects of a primary key can be configured using Data Annotations.

關於 fluent 應用程式開發介面Fluent API

您可以使用 fluent 應用程式開發的應用程式開發介面來設定資料庫中的主索引鍵條件約束的名稱。You can use the Fluent API to configure the name of the primary key constraint in the database.

class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .HasKey(b => b.BlogId)
            .HasName("PrimaryKey_BlogId");
    }
}

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