2014-02-17 137 views
0

我想配置2個實體之間的多對多關係,但我也想公開他們的外鍵。我只找到一個具體的解決方案在網上像以下:多對多關係EF與外鍵

modelBuilder.Entity<E1>() 
          .HasMany(t => t.E1s) 
          .WithMany(t => t.E2s) 
          .Map(m => 
          { 
           m.ToTable("E1E2"); 
           m.MapLeftKey("FKE1"); 
           m.MapRightKey("FKE2"); 
          }); 

但是Map離開,所以我沒有訪問他們,他們不會被填補,當我查詢右鍵不會從我的模型需要的屬性。所以,我無法訪問我的外鍵屬性。

希望我能解釋我的問題。任何人都可以提出其他選擇嗎?

回答

1

您可以創建具有兩個實體鍵的關聯模型:

public class AssociativeEntity 
{ 
    [Key] 
    public Guid AssociativeEntityId { get; set; } 
    public Guid Entity1Id { get; set; } 
    public Guid Entity2Id { get; set; } 

    [Display(Name = "Entity1", ResourceType = typeof(Resources.Language))] 
    public virtual Entity1 Entity1 { get; set; } 
    [Display(Name = "Entity2", ResourceType = typeof(Resources.Language))] 
    public virtual Entity2 Entity2 { get; set; } 
} 

實體1:

public class Entity1 
{ 
    [Key] 
    public Guid Entity1Id { get; set; } 

    /* Describe the other properties here */ 

    [Display(Name = "AssociativeEntities", ResourceType = typeof(Resources.Language))] 
    public virtual ICollection<AssociativeEntity> AssociativeEntities { get; set; } 
} 

實體2:

public class Entity2 
{ 
    [Key] 
    public Guid Entity2Id { get; set; } 

    /* Describe the other properties here */ 

    [Display(Name = "AssociativeEntities", ResourceType = typeof(Resources.Language))] 
    public virtual ICollection<AssociativeEntity> AssociativeEntities { get; set; } 
} 
+0

謝謝您的回答。通過「關聯模型」,你是指我將爲EF創建的中間表或連接表指定模型? – lbrahim

+1

是的。 modelBuilder的問題是您必須使用關聯模型的有限選項集。出於這個原因,我建議你手動創建模型。 –

+0

好的,謝謝。我會給它一個鏡頭。 – lbrahim