Search code examples
c#entity-frameworkbidirectional-relation

maintaining integrity in bidirectional relations and Entity Framework


I am looking for a best-practice regarding the maintaining of bidirectional relations between C# POCO's that are being persisted with Entity Framework.

A Family has zero to multiple familyMembers and a Person always has one family. Now when I instantiate a new Person and a new Family:

Person john = new Person();
Family adams = new Family();

I would then add the person to the family and vice versa. This takes:

adams.familyMembers.Add(john);
john.family = adams;

I am wondering if there is some better way to do this, because if I add a Person to a Family, that Persons family property should always be set to that family. If a developer forgets to do this you would end up with orphan objects.

Do I use full getters and setters to do this? Is there some automated way to do this?

Are there any special considerations when using Entity Framework to store these objects?

UML diagram

Thanks in advance


Solution

  • Entity framework could care less whether you set the other direction or not, it will still save it correctly. However, when using your domain model, you may want access to both navigation properties right away. This requires setting the property as you are doing. The solution I use for nearly all navigation collections is the following

    public class Family
    {
        public Family()
        {
            this.FamilyMembers = new List<Person>();
        }
        public IEnumerable<Person> FamilyMembers {get; protected set;}
    
        public void AddFamilyMember(Person person)
        {
            this.FamilyMembers.Add(person);
            person.Family = this;
        }
    }