1

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"));
       
jps
  • 20,041
  • 15
  • 75
  • 79
Garnett
  • 43
  • 7

1 Answers1

3

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));
Photonic
  • 1,316
  • 19
  • 31
  • This works. The second collection was the key. The actual code that worked for me was this: `code` modelBuilder.Entity() .HasMany(x => x.RelatedProducts) .WithMany(r => r.RelatedProductsOf) .UsingEntity( 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) ); – Garnett May 08 '22 at 12:35
  • I want to order in sub-products, so I added an ordering column to the ProductSet table, but I couldn't make an order in one way, can you help? – notcontrol Aug 29 '23 at 10:58