【问题标题】:Mapping child items of same class with Entity Framework Code First使用实体框架代码优先映射同一类的子项
【发布时间】:2011-06-14 23:30:16
【问题描述】:

我正在尝试使用 EF Code First 映射一个相当“标准”的类别模型

public class Category
{
    public int ID { get; set; }
    public int ParentID { get; set; }

    public string Name { get; set; }

    public Category ParentCategory { get; set; }
    public List<Category> ChildCategories { get; set; }
}

我有一些类似的东西:

modelBuilder.Entity<Category>()
    .HasOptional(t => t.ParentCategory)
    .WithMany()
    .HasForeignKey(t => t.ParentCategoryID)
    .WillCascadeOnDelete();

但这似乎没有照顾 ChildCategories??

我错过了什么吗?

为避免重复的问题参数,我遵循以下内容,但没有完全回答我的具体查询:

Code First Mapping for Entity Framework Hierarchy

Entity Framework CTP5 Code-First Mapping - Foreign Key in same table

【问题讨论】:

  • “但这似乎没有照顾 ChildCategories?”是什么意思?

标签: c# entity-framework-4 ef-code-first


【解决方案1】:

将您的实体更改为

public class Category
{
    public int ID { get; set; }
    public int? ParentID { get; set; }

    public string Name { get; set; }

    public virtual Category ParentCategory { get; set; }
    public virtual IList<Category> ChildCategories { get; set; }
}

使ParentID 可以为空并允许ChildCategories 延迟加载,将其设为虚拟。

【讨论】:

    猜你喜欢
    • 2011-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-06
    • 2012-03-12
    • 2011-04-21
    相关资源
    最近更新 更多