原文连接 https://blog.csdn.net/hhhhhhenrik/article/details/89216909
总结几种项目中遇到的一对多 多对多关系
1 基本的多对多关系
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");
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
2 同一个表建立两个多对多关系
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");
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
3 普通的一对多
public class npc
{
public string Name;
public int ContentId;//外键
}
public class Content
{
public string Name;
public ICollection<npc> npcs;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
4 同一个表建立两份一对多关系
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);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22