开发者

Setting up a recursive mapping with fluent for Entity Framework 4.1

How does one setup the mapping in fluent for this type?开发者_如何学C

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


I'm assuming that ParentId is not required as not every topic will have a parent.

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

then the mapping would look something similar to

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

And plugin on model binding:

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

I'd also recommend getting your hands on the EF Power Tools CTP. It's very helpful in learning and understanding how to create fluent configs.

Hope that helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜