سؤال

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

هل كانت مفيدة؟

المحلول 2

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;
    }
}

نصائح أخرى

I added this Answer since you asked about integrity checking. This feature in EF is widely overlooked.

Your POCOs can implement IValidatableObject

  public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 

Validate is called by EF on SaveChanges unless you have disabled it.

Context.Configuration.ValidateOnSaveEnabled = true; //default 

edit: SAMPLE CODE to get you started

 // Sample Implementation. 
         var validationResult = base.Validate(validationContext).ToList();  
        // validationResult.AddRange(xxx); // an example of mini call for common validations


         if (true) // the condition that leads to a validation error
         {
             var memberList = new List<string> { "PropertyName" }; // the name of the offending property
             var error = new ValidationResult("Error text goes here", memberList); // 
             validationResult.Add(error);
         }

         return validationResult;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top