I'm trying to create a many to many relationship between Product and Category with a joining table using EF 6.4.4 and MySQL 8, but unfortunately without success?
public class AppDbContext : DbContext
{
//Schema Tables
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<ProductCategory> ProductCategories { get; set; }
}
public abstract class BaseEntity
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
}
public class Product : BaseEntity
{
public virtual IList<Category> Categories { get; set; }
}
public class Category : BaseEntity
{
public virtual IList<Product> Products { get; set; }
}
now for the joining table I tried this:
public class ProductCategory
{
[Key, Column(Order = 1)]
public int ProductID { get; set; }
[Key, Column(Order = 2)]
public int CategoryID { get; set; }
public Product Product { get; set; }
public Category Category { get; set; }
}
and this:
public class ProductCategory : BaseEntity
{
public int ID { get; set; }
[ForeignKey(nameof(Product)), Column(Order = 1)]
public int ProductID { get; set; }
[ForeignKey(nameof(Category)), Column(Order = 2)]
public int CategoryID { get; set; }
public Product Product { get; set; }
public Category Category { get; set; }
}
and also this:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ProductCategory>().HasKey(x => new { x.ProductID, x.CategoryID });
}
the real problem is no matter what I do EF creates a duplicate joining table?
products
categories
productcategories
productcategory1 (duplicate)
Edit: apparently you can't do this according to this post and this one two, but there is a workaround.
// a workaround for the problem
public abstract class BaseEntity
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
}
public class Product : BaseEntity
{
public virtual IList<ProductCategory> ProductCategories { get; set; }
}
public class Category : BaseEntity
{
public virtual IList<ProductCategory> ProductCategories { get; set; }
}
public class ProductCategory
{
[Key, Column(Order = 1)]
public int ProductID { get; set; }
[Key, Column(Order = 2)]
public int CategoryID { get; set; }
public virtual Product Product { get; set; }
public virtual Category Category { get; set; }
}