Foreign Key 條件約束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.


依照慣例,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 APIFluent API

您可以使用 Fluent API 來設定關聯性的外部索引鍵條件約束名稱。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)
            .HasOne(p => p.Blog)
            .WithMany(b => b.Posts)
            .HasForeignKey(p => p.BlogId)

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; }