主索引鍵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 APIFluent API

您可以使用 Fluent API 來設定資料庫中的主索引鍵條件約束的名稱。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; }
}