Reputation: 2724
I'am using Entity-Framework and DDD.
If I have a reference between two entities, how should I handle persistence? Do updates cascade?
Suppose an Employer has reference to their Manager directly.
If I change the Employee.Manager.Name, and save the Employee, does the Manager’s Name get changed?
Upvotes: 3
Views: 484
Reputation: 7141
From a DDD point of view, any link to a Manager
from an Employee
should be by referencing the id only (assuming that Managers
are not part of the Employee
aggregate root and that Manager
is an aggregate root in its own right).
Essentially your property Employee.ManagerId
should return an id that allows you to retrieve the Manager
for that Employee
.
This will go against a lot of the 'goodness' that you get out of the box with Entity Framework, but this is usual for DDD. It's recommended to design your domain model around the business domain and not your database implementation.
Personally, I find that using EF entities as my domain model doesn't fit well when I'm practising DDD. Things like lazy loading navigation properties contradict good DDD practice. I tend to use document databases in my own projects these days, but when I have to use SQL, I restrict the EF entities to my persistence layer and code my repositories to return non-EF entities from my domain model instead.
Upvotes: 5
Reputation: 1147
Assuming you have the usual setup where your application uses one DbContext:
Yes, it will also save the referenced entity.
At the moment you set the Manager name, it will load the Manager reference and keep track of it. When you save changes by calling DbContext.SaveChanges
, it will commit all changes made to objects the DbContext
is keeping track off.
The only option to not have this behaviour is by using multiple DbContext
instances, but this opens a host of other problems (For instance: they are not aware of each others changes).
Upvotes: 1