Martin Milan
Martin Milan

Reputation: 6390

Entity Framework - Code first relationship mapping

I have a situation whereby I EntityA should have an property named "PropertyB" that points to an optional instance of EntityB, and EntityB has a property called PropertyA that points back to an EntityA instance - though NOT necessarily the same instance of entityA that we started with...

Any idea how to handle this in code first?

The exact scenario I am looking at involves OrganisationMembers and Orgainsations. OrganisationMembers are of course members of an organisation, which I model through having a property on the OrganisationMember pointing to the Organisation.

At the same time, Organisations have nominated person as a point of contact (or POC), which is modelled as a property of type OrganisationMember.

When I try and create a migration for this, I get told that EF can't determine which is the principal and which is the dependent.

Ideas anyone?

Upvotes: 0

Views: 68

Answers (1)

Chris
Chris

Reputation: 2019

Your EntityA, EntityB relation can be achieved like this:

public class EntityA
{
    public int Id { get; set; }

    public virtual EntityB EntityB { get; set; }
}

public class EntityB
{
    public int Id { get; set; }

    public virtual EntityA EntityA { get; set; }
}

And you need to tell Entity Framework about the relation:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<EntityA>()
        .HasOptional(x => x.EntityB)
        .WithOptionalDependent();

    modelBuilder.Entity<EntityB>()
        .HasOptional(x => x.EntityA)
        .WithOptionalDependent();
}

Upvotes: 1

Related Questions