2012-12-30 61 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