0

I have a model that looks like this:

public class Category
{
    public string Id { get; set; }
    public string Description { get; set; }
    public Category Parent { get; set; }
    public ICollection<Category> Children { get; set; }
    public ICollection<Product> Products { get; set; }
}

With a database table that looks like

Categories
    Id (PK varchar(5))
    Description (nvarchar(50))
    ParentId (FK varchar(5))

But Im stumped when it comes to setting up the mapping

modelBuilder.Entity<Category>()
    .HasMany(x => x.Children)
    .WithMany(x => x.Children)
    .Map(m =>
        {
            m.ToTable("Categories");
            m.MapLeftKey(x => x.Id, "Id");
            m.MapRightKey(x => x.Id, "ParentId");
        });

I can see why the mapping fails (StackOverflowException), but am unsure as to how to fix it. Any help would be greately appreciated.

This is using the latest release of EF (4.1?).

Thanks!

1 Answer 1

3

Why do you map many-to-many relation on the same navigation property? That is completely wrong. First your table obviously expect one-to-many relation. Even if you need many-to-many relation you cannot use the same navigation property for that.

Just try:

modelBuilder.Entity<Category>()
            .HasMany(x => x.Children)
            .WithOptional(y => y.Parent)
            .Map(m => m.MapKey("ParentId"));
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome. Thanks. Also need to remember to make those properties virtual.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.