0

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
  • 15,760
  • 14
  • 59
  • 71
Garnett
  • 33
  • 6

1 Answers1

1

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,236
  • 15
  • 28
  • 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