【问题标题】:Code First Mapping for Entity Framework Hierarchy实体框架层次结构的代码优先映射
【发布时间】:2011-08-29 04:57:02
【问题描述】:

我有一个看起来像这样的模型:

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?)。

谢谢!

【问题讨论】:

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


    【解决方案1】:

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

    试试吧:

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

    【讨论】:

    • 太棒了。谢谢。还需要记住将这些属性设为虚拟。
    猜你喜欢
    • 2011-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-12
    • 2011-04-21
    相关资源
    最近更新 更多