在ef核心中为同一实体设置外键

时间:2020-02-01 11:11:45

标签: c# entity-framework-core

我想为parent child中的同一实体类构建Entity Framework Core实体。

所以我有一个这样的实体:

public class Definition
{
    public int Id{ get; set; }
    public int ParentId { get; set; }
    public string Name { get; set; }
    public bool Active { get; set; }
}

我想将ParentId设置为将另一个Definition实体引用为父实体的外键。 我该怎么办?

谢谢

1 个答案:

答案 0 :(得分:0)

为父定义添加外键属性

 public class Definition
 {  
    [Key]
    public int Id{ get; set; }

    public int? ParentId { get; set; }
    public string Name { get; set; }
    public bool Active { get; set; }

    [ForeignKey("ParentId")]
    public virtual Definition ParentDefinition { get; set; }
}