我正在尝试使用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
答案 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
延迟加载,将其设为虚拟。