如果是我的话我会这样做
公司模式
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; }
}
在这个模型中,我说它与 CompanyCompetiorRelation 模型有 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; }
}
现在,我想说的是 CompanyCompetiorRelation 与公司模型有 2 个关系。
现在 Fluent API 的魔力将发挥作用
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);
}
在第一组FK上builder.Entity<CompanyCompetitorRelation>()
我是说它与许多公司都有一个 CompanyRelation,并且外键是 CompanyId
在第二组FK上builder.Entity<CompanyCompetitorRelation>()
我是说它作为与许多公司的一种 CompetitorRelation 关系,并且外键是 CompetitorId
这是它生成的
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");
希望这有助于理解
如果需要,您可以创建任意数量的内容,只需在 Fluent API 上将它们指向正确的方向即可
我认为在模型上也可以这样做,但我喜欢使用 FluentAPI