【问题标题】:How to define parent/children relation with EntityFrameworkCore?如何使用 EntityFrameworkCore 定义父/子关系?
【发布时间】:2021-12-12 02:42:12
【问题描述】:

我有一个项目使用EntityFrameworkCore 来访问数据库中的数据。

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

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 的关系?

【问题讨论】:

    标签: c# entity-framework .net-core entity-framework-core


    【解决方案1】:

    您必须为导航属性使用更简单的名称,否则 EF 会感到困惑。此代码已经过测试并且可以正常工作

    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; }
    
         }
    

    和数据库上下文

           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);
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-28
      • 2014-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-26
      相关资源
      最近更新 更多