EF将一个实体核心到多个表

时间:2020-11-02 16:19:13

标签: c# entity-framework ef-code-first

我在项目中使用EF Core。 Parent实体具有相同Child类的三个子集合。

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

我想将这些集合存储在db的多个表中,例如“ First”,“ Second”和“ Third”。

是否可以配置Ef核心?

1 个答案:

答案 0 :(得分:1)

使用EF Core 3.0。

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

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

要配置关系和表,我们使用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将类映射到数据库。

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

结果是一个像这样的表(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
);