I have been coding C# for a good while now, and I generally use Entity Framework and implement the repository pattern. The repository pattern tells us that we should generally only maintain and access repositories for our aggregate roots. Consider the following example, where Person is the root:
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Pet> Pets { get; set; }
}
public class Pet
{
public int ID { get; set; }
public string Name { get; set; }
}
The above model would mean that we should generally access pets through the PersonRepository. However, if I want to modify or add a pet to a person, I have never found an elegant way to do this.
In order to correctly identify what to update, I need to call
DbContext.Entry(myPet).State = EntityState.Modified;
However, this messes with my repository pattern. As far as I can see, I have three options:
- Create a PersonRepository.AttachPet(Pet pet) method. With a complex and deeper nested model, this quickly becomes cumbersome.
- Fetch DbContext directly to prepare the pet for modification or adding. However, I implemented a repository to NOT access DbContext directly.
- Modify PersonRepository.Update(Person person) to automatically update the state of underlying pets. Not very elegant either, and possibly a large task.
What am I missing here? Is there a better approach?