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

Mapping 实体框架层次结构的代码优先映射,mapping,ef-code-first,entity-relationship,entity-framework-4.1,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

我有一个这样的模型:

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; }
}
但是我在设置地图时遇到了麻烦

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");
        });
modelBuilder.Entity()
.HasMany(x=>x.Children)
.有许多(x=>x个孩子)
.Map(m=>
{
m、 ToTable(“类别”);
m、 MapLeftKey(x=>x.Id,“Id”);
m、 MapRightKey(x=>x.Id,“ParentId”);
});
我可以理解映射失败的原因(StackOverflowException),但不确定如何修复它。任何帮助都将不胜感激

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


谢谢

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

试试看:

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

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

试试看:

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

太棒了。谢谢还需要记住将这些属性虚拟化。谢谢还需要记住将这些属性设置为虚拟。