简体   繁体   English

如何使用 EntityFrameworkCore 定义父/子关系?

[英]How to define parent/children relation with EntityFrameworkCore?

I have a project that uses EntityFrameworkCore to access data from a database.我有一个使用EntityFrameworkCore从数据库访问数据的项目。

I am trying to create a parent/children relation for a single object (ie, Category ).我正在尝试为单个对象(即Category )创建父/子关系。 My object looks like this我的对象看起来像这样

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

The property ParentCategoryId is optional, but when set, it'll determine the parent of the current category. ParentCategoryId属性是可选的,但设置后,它将确定当前类别的父级。 At the same time, when the Children relation is included, I want to be able to pull all the categories where ParentCategoryId equal the id of the current category.同时,当包含Children关系时,我希望能够提取ParentCategoryId等于当前类别的 id 的所有类别。

I added the following code in the context to define the relations我在上下文中添加了以下代码来定义关系

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

So when the following code is called I want to get the ParentCategory and all Children of category id 10.因此,当调用以下代码时,我想获取ParentCategory和类别 ID 10 的所有Children项。

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

However, the above code gives me the following error但是,上面的代码给了我以下错误

Invalid column name 'ParentCategoryId1'." string

How can I correctly define the relations for ParentCategory and Children ?如何正确定义ParentCategoryChildren的关系?

You have to use more simple names for navigation properties, otherwise EF getting confused.This code was tested and working properly您必须为导航属性使用更简单的名称,否则 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; }

     }

and dbcontext和 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);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM