Summarize the one-to-many many-to-many relationship encountered in several projects
1 Basic many-to-many relationship
public class npc
{
public string Name;
public ICollection<Content> Contents;
}
public class Content
{
public string Name;
public ICollection<npc> npcs;
}
//fluent api
HasMany(m => m.Contents).WithMany(w => w.npcs).Map(m =>
{
m.ToTable("C_NPC_Content_Relation");
m.MapLeftKey("npcId");
m.MapRightKey("ContentId");
});
2 Establish two many-to-many relationships in the same table
public class npc
{
public string Name;
public ICollection<Content> Contents1;
public ICollection<Content> Contents2;
}
public class Content
{
public string Name;
public ICollection<npc> npcs;
}
//fluent api
HasMany(m => m.Contents1).WithMany(w => w.npcs).Map(m =>
{
m.ToTable("C_NPC_Content1_Relation");
m.MapLeftKey("npcId");
m.MapRightKey("ContentId");
});
HasMany(m => m.Contents2).WithMany().Map(m =>
{
m.ToTable("C_NPC_Content2_Relation");
m.MapLeftKey("npcId");
m.MapRightKey("ContentId");
});
3 Ordinary one-to-many
public class npc
{
public string Name;
public int ContentId;//外键
}
public class Content
{
public string Name;
public ICollection<npc> npcs;
}
4 Establish two one-to-many relationships in the same table
public class npc
{
public string Name;
public int ContentId_1;//外键1
public int ContentId_2;//外键2
}
public class Content
{
public string Name;
public ICollection<npc> npcs_1;
public ICollection<npc> npcs_2;
}
//fluent api(npc)
this.HasRequired(t => t.Content)
.WithMany(t => t.npcs_1)
.HasForeignKey(t => t.ContentId_1)
.WillCascadeOnDelete(false);
this.HasOptional(t => t.Content)
.WithMany(t => t.npcs_2)
.HasForeignKey(t => t.ContentId_2)
.WillCascadeOnDelete(false);