[英]EF Core one entity to several tables
我在我的項目中使用 EF Core。 Parent
實體具有相同Child
類的三個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; }
}
我想將這些集合存儲在數據庫中的幾個表中,例如“第一”、“第二”和“第三”。
是否可以配置 Ef 核心來這樣做?
使用 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");
});
});
}
我們使用擁有的類型將我們的類映射到數據庫。
為了將數據保存在三個不同的表中,我們將 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
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.