外部索引鍵條件約束Foreign Key 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).

針對每個關聯性模型中引進的外部索引鍵條件約束。A foreign key constraint is introduced for each relationship in the model.

慣例Conventions

根據慣例,foreign key 條件約束會命名為FK_<dependent type name>_<principal type name>_<foreign key property name>By convention, foreign key constraints are named FK_<dependent type name>_<principal type name>_<foreign key property name>. 複合外部索引鍵<foreign key property name>變得的外部索引鍵屬性名稱的底線分隔清單。For composite foreign keys <foreign key property name> becomes an underscore separated list of foreign key property names.

資料註釋Data Annotations

無法使用資料註解來設定外部索引鍵條件約束名稱。Foreign key constraint names cannot be configured using data annotations.

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

若要設定關聯性的外部索引鍵條件約束名稱,您可以使用 fluent 應用程式開發的應用程式開發介面。You can use the Fluent API to configure the foreign key constraint name for a relationship.

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

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Post>()
            .HasOne(p => p.Blog)
            .WithMany(b => b.Posts)
            .HasForeignKey(p => p.BlogId)
            .HasConstraintName("ForeignKey_Post_Blog");
    }
}

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

    public List<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int BlogId { get; set; }
    public Blog Blog { get; set; }
}