Search code examples
entity-framework-coremany-to-many

EF Core 5 many to many relationship to the same table?


A product can have many other related products. The following creates the join table perfectly but when I add a product to another product's RelatedProducts I get the following error on save: 'The value of 'ProductAssociation.ProductID' is unknown when attempting to save changes. This is because the property is also part of a foreign key for which the principal entity in the relationship is not known.'

modelBuilder.Entity<Product>()
                .HasMany(x => x.RelatedProducts)
                .WithMany(r => r.RelatedProducts)
                .UsingEntity<ProductAssociation>(
                    x => x.HasOne(p => p.RelatedProduct).WithMany().HasForeignKey(f => f.RelatedProductID),
                    x => x.HasOne(p => p.Product).WithMany().HasForeignKey(f => f.ProductID).OnDelete(DeleteBehavior.NoAction),
                    x => x.ToTable("ProductAssociations"));
       

Solution

  • I think this is a similar answer Entity Framework Core 2.0 many-to-many relationships same table

    I also solved it with that provide link above like this in core 3+.

    Product table

    public class Product
    {
        // Other properties members ....
        
        public ICollection<Product> Products { get; set; }
        public ICollection<Product> ProductOf { get; set; }
    }
    

    Product Association table "ProductSet"

    public class ProductSet
    {
        public int ProductId { get; set; }
        public int SubProductId { get; set; }
    }
    

    OnModelCreating()

    modelBuilder.Entity<Product>()
        .HasMany(e => e.Products)
        .WithMany(e => e.ProductOf)
        .UsingEntity<ProductSet>(
            e => e.HasOne<Product>().WithMany().HasForeignKey(e => e.ProductId),
            e => e.HasOne<Product>().WithMany().HasForeignKey(e => e.SubProductId));