替代索引鍵 (唯一條件約束)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 APIFluent API

您可以使用 Fluent API 來設定其他的索引鍵的索引和條件約束名稱。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; }
}