I'm not sure if I've got my wording correct (which might be why I'm struggling to find results).
Here's what I'm trying to achieve:
I'd like to be able to be able to add a collection of related products (Product B, Product C) to Product A. I'd like it so that when you then look at Product B, the related products reflect what's been added on A (as in you would see Product A and Product C). Does there have to be a separate table just for the 'related' relationships? I'm guessing there's a simple way to do this.
public class Product
{
public int ProductId { get; set; }
public string DefinitionUri { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<Product> RelatedProducts { get; set; }
}
You can use the property as you defined it, but you should tell EF that it is a many to many association, e.g. like so:
entry.HasMany(p => p.RelatedProducts)
.WithMany()
.Map(m => m.MapLeftKey("ProductId")
.MapRightKey("ProductIdReleated"));
Now Ef will create a junction table with two FKs to Product. Without this mapping it will create a Product table with an FK to itself, i.e. a 1-n association.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With