0

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?

Martin Milan
  • 6,346
  • 2
  • 32
  • 44
  • Can you include the code of the `OrganisationMembers` and `Organisation` classes? – DF_ Mar 22 '16 at 00:43
  • 1
    I think this may be what you're looking for http://stackoverflow.com/questions/18331231/bi-directional-relationships-in-entity-framework-code-first – paste Mar 22 '16 at 00:53
  • Deif - paste's question answered mine, so no need. Thanks for taking a look. Paste - cheers mate... – Martin Milan Mar 22 '16 at 10:10

1 Answers1

1

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();
}
Chris
  • 2,009
  • 1
  • 16
  • 25