Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symmetric relationship in EF Code first

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; }
}
like image 901
Nick Darvey Avatar asked May 16 '26 01:05

Nick Darvey


1 Answers

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.

like image 128
Gert Arnold Avatar answered May 19 '26 03:05

Gert Arnold