Code First Mapping for Entity Framework Hierarchy

2019-03-04 15:54发布

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条回答
小情绪 Triste *
2楼-- · 2019-03-04 16:36

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"));
查看更多
登录 后发表回答