首先在代码中将多对多表的PK映射为FK到任何多对多表
本文关键字:映射 FK 任何多 PK 代码 | 更新日期: 2023-09-27 17:50:07
这些是我的表:CFFPart, Disp, CFFPartDisp, Expert, cffpartdisexpert,CFFPart - disp与CFFPart &Disp .
ToTable("Discipline", "dbr");
Property(t => t.Id).HasColumnName("DispID");
Property(t => t.Text).HasColumnName("DisPName");
HasMany(t => t.CFFParts).WithMany().Map(m => m.MapLeftKey("DisPID").MapRightKey("CFFPartID").ToTable("CFFPartDisP", "dbr"));
cffpartdisexpert与Expert & &;CFFpartDisP我如何写这个映射在代码第一?
您必须将CFFPartDisp
公开为模型中的实体类。您不能将其用作CFFPart
和Disp
之间的链接表,并在您的问题中使用Fluent映射。CFFPart
和Disp
之间的关系不是多对多关系(严格意义上的EF)。相反,您必须以CFFPartDisp
作为中间实体创建两个一对多关系。然后,您可以将CFFPartDisp
和Expert
之间的关系作为第三个关系链接到这个中间实体。
CFFPartDisp
实体可以像这样:
public class CFFPartDisp
{
public int ID { get; set; }
public int CFFPartID { get; set; }
public CFFPart CFFPart { get; set; }
public int DispID { get; set; }
public Disp Disp { get; set; }
public ICollection<Expert> Experts { get; set; }
}
CFFPart
和Disp
实体需要引用CFFPartDisp
的集合:
public class CFFPart
{
public int ID { get; set; }
public ICollection<CFFPartDisp> CFFPartDisps { get; set; }
}
public class Disp
{
public int ID { get; set; }
public ICollection<CFFPartDisp> CFFPartDisps { get; set; }
}
Expert
也需要CFFPartDisp
的集合来建立CFFPartDisp
和Expert
之间的多对多关系:
public class Expert
{
public int ID { get; set; }
public ICollection<CFFPartDisp> CFFPartDisps { get; set; }
}
使用这些实体,你可以创建三种关系:
modelBuilder.Entity<CFFPartDisp>()
.HasRequired(cpd => cpd.CFFPart)
.WithMany(cp => cp.CFFPartDisps)
.HasForeignKey(cpd => cpd.CFFPartID);
modelBuilder.Entity<CFFPartDisp>()
.HasRequired(cpd => cpd.Disp)
.WithMany(cp => cp.CFFPartDisps)
.HasForeignKey(cpd => cpd.DispID);
modelBuilder.Entity<CFFPartDisp>()
.HasMany(cpd => cpd.Experts)
.WithMany(e => e.CFFPartDisps)
.Map(m =>
{
m.MapLeftKey("CFFPartDispID");
m.MapRightKey("ExpertID");
m.ToTable("CFFpartDisPExpert");
});