How to create a category table that has SubCategories using EF Core Code-First?

Viewed 632

I have created a simple table named "Category". Each category could have one or more subcategories or they could have no category.

I can't do it using EF core Code-First in ASP.NET 5. Would you mind help me to complete this table?

public int Id {get;set;}
public string Title {get;set;}
public int? parentId {get;set;}

How to set the relationship?

3 Answers

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

}

and db context

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

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

I would suggest setting up 2 tables (classes)

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

And then another one:

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

    public int CategoryId {get;set;}

    [ForeignKey(nameof(CategoryId))]
    public Category Category {get;set}

    public string SubCategoryTitle {get;set;}
}

More information under Data Annotations in EF Core

Edit: This holds true, when at some point in time down the road the Category might have different fields than the SubCategory. If not, then a self-referencing table would be a nicer approach like Johnathan Barclay and Serge are suggesting.

So you want One to many relationships (Category to have many SubCategory).

Try this below code:-

public class Category{

public int Id { get; set; }
public string Title {get;set;}
public List<SubCategory> SubCategories{ get; set; }

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

    public string Text { get; set; }

    //Navigation
    public int CategoryId { get; set; }

    public Category Category{ get; set; }

}
    
Related