Search code examples
entity-frameworkef-code-firstfluent-interfacecomposite-primary-key

Fluent API map composite pattern object


I am trying to map a composite object using FluentAPI on entity framework 5.0 for the following model:

public class Category
{
    public int CategoryId { get; set; }
    public string CategoryName { get; set; }
    public virtual ICollection<Category> Children { get; set; }
}

So far tried many ways that didn't work well, such as the following:

HasKey(t => t.CateroryId);
HasOptional(c => c.Children)
   .WithMany()
   .HasForeignKey(c => c.CateroryId);

Any idea how I might do that?


Solution

  • If I've understood what you're going for - a Category is able to have many categories as children.

    I've done this in the past using a similar foreign key mapping and some additional properties, although there may be a way to do it using independent association.

    Adding additional properties to your Category so we can keep track of the parent/child relationship:

    public class Page
    {
        public int CategoryId { get; set; }
        public string CategoryName { get; set; }
        public int? ParentID { get; set; } // Nullable (Parent is optional).
    
        // Navigation properties
        public virtual Category Parent { get; set; } // Optional Parent
        public virtual ICollection<Category> Children { get; set; }
    }
    

    You should then be able to configure like so (depending on where your mappings are set):

    this.HasMany(c => c.Children)        // Many Children
        .WithOptional(c => c.Parent)     // Optional Parent
        .HasForeignKey(x => x.ParentID);