EF核心:在同一表格中的项目之间创建链接



假设我有一个公司列表:

公司 CompanyID
公司A 1
公司B 2
公司C 3
公司D 4

如果我这样做,我会像这个一样做

公司型号

public class Company
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<CompanyCompetitorRelation> CompanyRelation { get; set; }
public virtual ICollection<CompanyCompetitorRelation> CompetitorRelation { get; set; }
}

在这个模型中,我说它与CompanyCompetitorRelation模型有2个关系。

现在是公司竞争对手关系模型

public class CompanyCompetitorRelation
{
public int CompanyId { get; set; }
public int CompetitorId { get; set; }
public virtual Company CompanyRelation { get; set; }
public virtual Company CompetitorRelation { get; set; }
}

现在,我要说的是,一个CompanyCompetitorRelation与公司模型有2种关系。

现在FluentAPI 的魔力开始显现

protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Company>()
.HasKey(e => e.Id);
builder.Entity<CompanyCompetitorRelation>()
.HasKey(e => new { e.CompanyId, e.CompetitorId });
builder.Entity<CompanyCompetitorRelation>()
// CompanyCompetitorRelation property
.HasOne(e => e.CompanyRelation)
// Company property
.WithMany(e => e.CompanyRelation) 
// Set the property that is FK for this relation
.HasForeignKey(e => e.CompanyId); 
builder.Entity<CompanyCompetitorRelation>()
// CompanyCompetitorRelation property
.HasOne(e => e.CompetitorRelation) 
// Company property
.WithMany(e => e.CompetitorRelation) 
// Set the property that is FK for this relation
.HasForeignKey(e => e.CompetitorId); 
}

builder.Entity<CompanyCompetitorRelation>()的第一组FK上,我说它与许多公司都有一个公司关系,并且是外国的密钥是CompanyId

关于CCD_ 2的第二组FK我的意思是,这是与许多公司的一种竞争关系,而且是外国的关键是竞争对手ID

这就是它生成的原因

migrationBuilder.CreateTable(
name: "Company",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Company", x => x.Id);
});
migrationBuilder.CreateTable(
name: "CompanyCompetitorRelation",
columns: table => new
{
CompanyId = table.Column<int>(type: "int", nullable: false),
CompetitorId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_CompanyCompetitorRelation", x => new { x.CompanyId, x.CompetitorId });
table.ForeignKey(
name: "FK_CompanyCompetitorRelation_Company_CompanyId",
column: x => x.CompanyId,
principalTable: "Company",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_CompanyCompetitorRelation_Company_CompetitorId",
column: x => x.CompetitorId,
principalTable: "Company",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_CompanyCompetitorRelation_CompetitorId",
table: "CompanyCompetitorRelation",
column: "CompetitorId");

希望这将有助于理解

如果需要,您可以创建任意数量的,只需在FluentAPI 上将它们指向正确的方向即可

我认为这在模型上也是可能的,但我喜欢使用FluentAPI

最新更新