使用流畅的Entity Framework 4.1设置递归映射

时间:2011-06-26 06:43:07

标签: entity-framework entity-framework-4.1 fluent

如何为这种类型设置流利的映射?

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

1 个答案:

答案 0 :(得分: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。这对学习和理解如何创建流畅的配置非常有帮助。

希望有所帮助。