【问题标题】:Self-referencing in code-first POCO classes in Entity Framework [duplicate]实体框架中代码优先 POCO 类中的自引用 [重复]
【发布时间】:2016-04-14 23:52:42
【问题描述】:
我有模特:
public class Category
{
[Key]
public int CategoryId { get; set; }
public string Name { get; set; }
public int Parent { get; set; }
}
我想先使用代码创建一个数据库,如何为 Parent 添加外键? (创建关系Parent->CategoryId)
【问题讨论】:
标签:
c#
entity-framework
model-view-controller
【解决方案1】:
public class Category
{
[Key]
public int CategoryId { get; set; }
public string Name { get; set; }
public int? ParentID { get; set; }
[ForeignKey("ParentID")]
public virtual List<Category> Subcategories { get; set; }
}