2012-12-30 63 views
0

映射为FK任何东西多对多表这些都是我的表:CFFPart,详细显示,CFFPartDisp,专家,CFFpartDispExpert, CFFPartDisp有很多 - CFFPart &详细显示之间的多对多关系。PK中的代码首先

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")); 

CFFpartDisPExpert有很多 - 专家& CFFpartDisP 之间一对多的关系我怎样写映射此代码先?

+0

你能写出更多的细节?可能是显示数据库图。你的问题是什么? –

+0

@KirillBestemyanov - 我从Code First的两个表(CFFPart和Disp)创建一个组合表(CFFpartDisp)。数据库当前使用组合表的ID(主键)与专家建立关系。我不知道如何使用CodeFirst将组合表ID与专家ID进行映射?任何建议,将不胜感激。 – akki

回答

1

您必须将CFFPartDisp作为模型中的实体类公开。您不能将它用作CFFPartDisp之间的链接表,并在您的问题中使用Fluent映射。 CFFPartDisp之间的关系不是多对多的关系(在严格的EF意义上)。相反,您必须创建两个与CFFPartDisp作为中间实体的一对多关系。然后,您可以将您与CFFPartDispExpert之间的关系作为第三关系链接到此中间实体。

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; } 
} 

CFFPartDisp实体将需要集合指的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集合以及建立CFFPartDispExpert之间的多对多关系:

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"); 
    }); 
+0

非常感谢你:) – akki