替代索引鍵 (唯一條件約束)Alternate Keys (Unique Constraints)

注意

本節中的設定是一般適用於關聯式資料庫。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).

針對每個模型中的替代索引鍵引進 unique 條件約束。A unique constraint is introduced for each alternate key in the model.

慣例Conventions

依照慣例,會引進其他的索引鍵的條件約束與索引將被命名為AK_<type name>_<property name>By convention, the index and constraint that are introduced for an alternate key will be named AK_<type name>_<property name>. 對於複合替代索引鍵<property name>變成屬性名稱的底線分隔清單。For composite alternate keys <property name> becomes an underscore separated list of property names.

資料註釋Data Annotations

Unique 條件約束不可以使用資料註解來設定。Unique constraints can not be configured using Data Annotations.

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

您可以使用 fluent 應用程式開發的應用程式開發介面來設定其他的索引鍵的索引和條件約束名稱。You can use the Fluent API to configure the index and constraint name for an alternate key.

class MyContext : DbContext
{
    public DbSet<Car> Cars { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Car>()
            .HasAlternateKey(c => c.LicensePlate)
            .HasName("AlternateKey_LicensePlate");
    }
}

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