2011-06-26 96 views
3

如何爲此類型設置流暢映射?使用Fluent爲實體框架設置遞歸映射4.1

public class Topic 
{ 
    public int Id { get; set; }  
    public string Title { get; set; }  
    public virtual ICollection<Topic> Children { get; set; }  
    public int ParentId { get; set; }  
    public Topic Parent { get; set; }  
    public virtual ICollection<Topic> Related { get; set; } 
} 

回答

7

我假設ParentId不是必需的,因爲不是每個主題都會有父項。

public class Topic 
{ 
    public int Id { get; set; } 
    public string Title { get; set; } 
    public int? ParentId { get; set; } 
    public Topic Parent { get; set; } 
    public virtual ICollection<Topic> Children { get; set; } 
    public virtual ICollection<Topic> Related { get; set; } 
} 

則映射將類似於東西

public class TopicMap : EntityTypeConfiguration<Topic> 
{ 
    public TopicMap() 
    { 
     HasKey(t => t.Id); 

     Property(t => t.Title) 
      .IsRequired() 
      .HasMaxLength(42); 

     ToTable("Topic"); 
     Property(t => t.Id).HasColumnName("Id"); 
     Property(t => t.Title).HasColumnName("Title"); 
     Property(t => t.ParentId).HasColumnName("ParentId"); 

     // Relationships 
     HasOptional(t => t.Parent) 
      .WithMany() 
      .HasForeignKey(d => d.ParentId); 
     //Topic might have a parent, where if it does, has a foreign key 
     //relationship to ParentId 
    } 
} 

和插件的型號綁定:

protected override void OnModelCreating(DbModelBuilder modelBuilder) 
{ 
    modelBuilder.Configurations.Add(new TopicMap()); 
    //modelBuilder.Configurations.Add(new TopicChildrenMap()); ..etc 
    //modelBuilder.Configurations.Add(new TopicRelatedMap()); ..etc 
} 

我也建議你的手在the EF Power Tools CTP。這對學習和理解如何創建流暢的配置非常有幫助。

希望有所幫助。

+0

我這隻需添加HasOptional(p => p.Parent)就足夠了。否則,WithMany會導致主題顯示爲兒童,並在他們無法訪問時顯示相關內容。 – Steven

+0

是否可以這樣做,以便兒童以級聯的方式被刪除?父母如何自動設置? – Steven

+0

謝謝,這也回答了我的問題。不過,我想知道,如果「Children」和「Parent」屬性名稱是該語言的必需約定,或者它們的名稱可以更改。 –