实体框架层次结构的代码优先映射

时间:2011-05-19 20:38:22

标签: mapping ef-code-first entity-relationship entity-framework-4.1

我的模型看起来像这样:

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; }
}

使用类似于

的数据库表
Categories
    Id (PK varchar(5))
    Description (nvarchar(50))
    ParentId (FK varchar(5))

但是在设置映射

时我很难过
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");
        });

我可以看到为什么映射失败(StackOverflowException),但我不确定如何解决它。任何帮助都会受到高度赞赏。

这是使用最新版本的EF(4.1?)。

谢谢!

1 个答案:

答案 0 :(得分:3)

为什么要在同一导航属性上映射多对多关系?那是完全错误的。首先,你的表显然期望一对多的关系。即使您需要多对多关系,也不能使用相同的导航属性。

试试吧:

modelBuilder.Entity<Category>()
            .HasMany(x => x.Children)
            .WithOptional(y => y.Parent)
            .Map(m => m.MapKey("ParentId"));