如何定义与 EntityFrameworkCore 的 parent/children 关系?

How to define parent/children relation with EntityFrameworkCore?

我有一个项目使用 EntityFrameworkCore 从数据库访问数据。

我正在尝试为单个对象(即 Category)创建 parent/children 关系。我的对象看起来像这样

public class Category
{
    public int Id { get; set;}

    public string Name { get; set; }

    public int? ParentCategoryId { get; set; }

    public Category ParentCategory { get; set; }

    public ICollection<Category> Children { get; set; }
}

属性 ParentCategoryId 是可选的,但设置后,它将确定当前类别的父类别。同时,当包含 Children 关系时,我希望能够提取所有 ParentCategoryId 等于当前类别 ID 的类别。

我在上下文中添加了以下代码来定义关系

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);
    builder.Entity<Category>(cat =>
    {
        cat.HasMany(x => x.Children).WithOne().HasForeignKey(x => x.ParentCategoryId);
        cat.HasOne(x => x.ParentCategory).WithOne();
    });
}

因此,当调用以下代码时,我想获取类别 ID 为 10 的 ParentCategory 和所有 Children

var category = _context.Categories.Where(cat => cat.Id == 10)
                       .Include(x => x.ParentCategory)
                       .Include(x => x.Children)
                       .ToList();

但是,上面的代码给我以下错误

Invalid column name 'ParentCategoryId1'." string

如何正确定义 ParentCategoryChildren 的关系?

您必须为导航属性使用更简单的名称,否则 EF getting confused.This 代码已经过测试并且可以正常工作

public class Category
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public int? ParentId { get; set; }
        public virtual Category Parent { get; set; }

        public virtual ICollection<Category> Children { get; set; }

     }

和 dbcontext

       public virtual DbSet<Category> Categories { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {

            modelBuilder.Entity<Category>()
            .HasOne(s => s.Parent)
            .WithMany(m => m.Children)
            .HasForeignKey(e => e.ParentId);

            OnModelCreatingPartial(modelBuilder);
        }