Paul D'Ambra
Paul D'Ambra

Reputation: 7814

Specify the name of a parent-child join table using EF6 Code-First EntityTypeConfiguration

I'm using code first to create my DB but have to match a given schema.

I have an Org entity (simplified here) an Org can have many children of type org

public class Org 
{
  public int Id {get;set;}
  public virtual IList<Org> Children{get;set;}
}

I want to generate an Org table and a table called OrgRelationship which has two columns ParentId and ChildId. The data is being provided to us in that format but I'd really like EF to expand the table into this model...

Is it possible to generate this join table just with an EntityTypeConfiguration on model builder? Do I have to have an OrgRelationship class?

This doesn't seem to cut it

public class OrgMap : EntityTypeConfiguration<Org>
{
    public OrgMap()
    {
        HasKey(n => n.Id);
        HasMany(n => n.Children);
    }
}

Upvotes: 0

Views: 453

Answers (1)

bricelam
bricelam

Reputation: 30345

You can configure the join table using the following calls.

HasMany(n => n.Children).WithMany().Map(
    m => m.ToTable("OrgRelationship").MapLeftKey("ParentId").MapRightKey("ChildId"));

Upvotes: 2

Related Questions