使用Entity Framework Code First映射相同类的子项

时间:2011-06-14 23:30:16

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

我正在尝试使用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

1 个答案:

答案 0 :(得分:3)

将您的实体更改为

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延迟加载,将其设为虚拟。