如何在Entity Framework Core中配置与同一表的一对一关系

时间:2019-08-19 04:52:45

标签: entity-framework entity-framework-6 entity-framework-core

我的模型如下:

 public class Category : BaseEntity
    {
        public string Name { get; set; }
        public virtual Category Parent { get; set; }
        public string Description { get; set; }
    }

Parent属性与同一张表相关。我该如何配置?

我在想像这样的东西:

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Category>()
         .HasOne(a => a.Parent)
         .OnDelete(false);
        }

我是实体框架核心的新手,请帮帮我!

1 个答案:

答案 0 :(得分:0)

解决者:

public class Category : BaseEntity
    {
        public string Name { get; set; }
        public int? ParentId{ get; set; } /*added*/
        [ForeignKey("ParentId")]   /*added*/
        public virtual Category Parent { get; set; }
        public string Description { get; set; }
    }