How should I handle persistence for referenced entities?

 ̄綄美尐妖づ 提交于 2019-12-04 04:34:14

问题


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?


回答1:


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.




回答2:


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).



来源:https://stackoverflow.com/questions/28815732/how-should-i-handle-persistence-for-referenced-entities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!