Many to many relation with the same table with EF4.3 Code First

594 Views Asked by At

How to make a configuration with this schema?

CREATE TABLE Entity
(
    Id int identity primary key,
    Name nvarchar(30)
)

CREATE TABLE Member
(
    ParentEntityId references Entity(Id),
    ChildEntityId references Entity(Id)
)
1

There are 1 best solutions below

0
Slauma On

Like so:

Model class:

public class Entity
{
    public int Id { get; set; }
    public string Name { get; set; }

    public ICollection<Entity> Parents { get; set; }
    public ICollection<Entity> Children { get; set; }
}

Mapping:

modelBuilder.Entity<Entity>()
    .HasMany(e => e.Parents)
    .WithMany(e => e.Children)
    .Map(m =>
    {
        m.ToTable("Member");
        m.MapLeftKey("ParentEntityId");
        m.MapRightKey("ChildEntityId");
    });