EFCore6 Many to Many relationship with only 2 tables

Viewed 14

I'm new to EFCore 6, and the Fluent API. I want to specify the many-to-many relationship between categories within a product catalog. Each category can be a parent to many other categories, and can be a child to many categories as well. My table structure is as follows:

tblCategories CategoryId Name

tblCategoriesToCategories ParentCategoryId CategoryId

Both columns in the join table refer back to tblCategories.CategoryId, and it's just whether you are looking for parents or children to determine which column will match up. As you can imagine, this makes it difficult to discern how to translate this into Fluent API. I've got this so far for my models (across different files, of course) but it is not correct.

[Table("tblCategories")]    
public class Category
    {
    public int CategoryId { get; set; }
    public string Name { get; set; } = string.Empty;
    
    public virtual List<CategoriesToCategories> ChildCategories { get; set; } = new List<CategoriesToCategories>();
    
    public virtual List<CategoriesToCategories> ParentCategories { get; set; } = new List<CategoriesToCategories>();
}

[Table("tblCategoriesToCategories")]
    public class CategoriesToCategories
    {
    [ForeignKey("CategoryId")]
    public int ParentCategoryId { get; set; }

    [ForeignKey("CategoryId")]
    public int CategoryId { get; set; }
    
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
        modelBuilder.Entity<CategoriesToCategories>()
            .HasKey(c => new {c.ParentCategoryId, c.CategoryId, c.SiteId})
            ;
        
        modelBuilder.Entity<Category>()
            .HasMany<CategoriesToCategories>(c => c.ChildCategories);
            
        modelBuilder.Entity<Category>()
            .HasMany<CategoriesToCategories>(c => c.ParentCategories);

}

0 Answers
Related