Code First Mapping for Entity Framework Hierarchy

匆匆过客 提交于 2019-12-02 20:17:37

问题


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:


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"));


来源:https://stackoverflow.com/questions/6064591/code-first-mapping-for-entity-framework-hierarchy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!