EF Core 一个实体到多个表

EF Core one entity to several tables

我在我的项目中使用 EF Core。 Parent 实体具有三个相同 Child class.

的子集合
public class Parent
{
    public virtual List<Child> FirstCollection { get; set; }
    public virtual List<Child> SecondCollection { get; set; }
    public virtual List<Child> ThirdCollection { get; set; }
}

public class Child
{
    public int Order { get; set; }
    public string Name { get; set; }
}

我想将这些集合存储在数据库中的几个表中,例如“First”、“Second”和“Third”。

是否可以配置 Ef 核心来这样做?

使用 EF Core 3.0。

我们开始通过向 Parent 添加主键来定义关系 class:

public class Parent
{
    public int Id { get; set; }
    public List<Child> FirstCollection { get; set; }
    public List<Child> SecondCollection { get; set; }
    public List<Child> ThirdCollection { get; set; }
}

要配置关系和 tables,我们使用 Fluent API。我们覆盖 OnModelCreating 方法:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Parent>(entity =>
    {
        entity.OwnsMany(x => x.FirstCollection, a =>
        {
            a.ToTable("First");
            a.HasKey("Id");
        });

        entity.OwnsMany(x => x.SecondCollection, a =>
        {
            a.ToTable("Second");
            a.HasKey("Id");
        });

        entity.OwnsMany(x => x.ThirdCollection, a =>
        {
            a.ToTable("Third");
            a.HasKey("Id");
        });
    });
}

我们已经使用 Owned Types 将我们的 class 映射到数据库。

为了在三个不同的 table 中保存数据,我们将 ToTable 方法添加到配置中。

结果是这样的 table (SQLite):

CREATE TABLE "First" (
    "Id" INTEGER NOT NULL CONSTRAINT "PK_First" PRIMARY KEY AUTOINCREMENT,
    "Order" INTEGER NOT NULL,
    "Name" TEXT NULL,
    "ParentId" INTEGER NOT NULL,
    CONSTRAINT "FK_First_Parents_ParentId" FOREIGN KEY ("ParentId") REFERENCES "Parents" ("Id") ON DELETE CASCADE
);