Reputation: 6390
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
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