Question

I am having difficulty setting up bi-directional self-referencing many-to-many mapping using EF in ASP.NET MVC4

I have:

modelBuilder.Entity<Item>()
    .HasMany(i => i.ChildItems)
    .WithMany()
    .Map(m => m.MapLeftKey("ItemID")
        .MapRightKey("ChildItemId")
        .ToTable("ItemChildItems"));

So I am able to query Item.ChildItems no problem.

However, I also want Item.Parents

I am sure there must be an obvious solution to this but I am missing it. I have tried creating another entity Parent : Item and a separate mapping. I have also tried operating with two mapping tables. Both these become messy and I haven't managed to make them work anyway.

I don't require any payload in the relationship.

Any help greatly appreciated!

Was it helpful?

Solution

Have you tried this?

modelBuilder.Entity<Item>()
    .HasMany(i => i.ChildItems)
    .WithMany(i => i.Parents) // associate the parent items here
    .Map(m => m.MapLeftKey("ItemID")
        .MapRightKey("ChildItemId")
        .ToTable("ItemChildItems"));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top