2012-09-03 53 views
1

我有一個簡單的入門級車型EF5的Code First:強制多對多遞歸關係

public class Entry 
{ 
    public int Id { get; set; } 
    public DateTime Modified { get; set; } 
    public DateTime Created { get; set; } 

    // Related entries 
    public virtual ICollection<Entry> RelatedEntries { get; set; } 

    // The nodes this entry contains 
    public virtual ICollection<Node> Nodes { get; set; } 

    // The category this entry is located in 
    public virtual Category Category { get; set; } 
} 

我希望我的進入能夠有相關的條目列表,問題是它只是增加了一個FK Entry_id的條目表,我想創建一個新表,其中包含一個多對多的關係,例如

Entry_Id | Related_Entry_Id 
     01 | 02 
     01 | 03 
     01 | 06 
     02 | 04 

這樣就會使進入01與02,03和06,並進入02與04 。

回答

3

您可以用流利的API指定的關係類型的許多一對多(而不是一個一對多的關係,其中EF假設默認):

public class MyContext : DbContext 
{ 
    //... 
    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<Entry>() 
      .HasMany(e => e.RelatedEntries) 
      .WithMany() 
      .Map(m => 
      { 
       m.MapLeftKey("Entry_Id"); 
       m.MapRightKey("Related_Entry_Id"); 
       m.ToTable("EntryRelations"); 
      }); 
    } 
} 
+0

謝謝!這工作像一個魅力。 – gosukiwi