Search code examples
c#entity-framework-corecode-first

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


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?


Solution

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