Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up a recursive mapping with fluent for Entity Framework 4.1

How does one setup the mapping in fluent for this type?

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; }
}
like image 269
Steven Avatar asked May 30 '26 13:05

Steven


1 Answers

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.

like image 131
Khepri Avatar answered Jun 01 '26 15:06

Khepri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!