How should I handle persistence for reference objects?

I am using Entity-Framework and DDD.

If I have a link between two objects, how do I handle persistence? Are cascades updated?

Suppose that the Employer has a link to their Manager directly.

If I change Employee.Manager.Name and save Employee, will the manager name change?

+3
source share
2 answers

From the DDD point of view, any reference to the Manager from Employee should only be associated with an identifier (assuming that Managers are not part of the root of the Employee aggregate and that Manager is the aggregate root in its own right).

Essentially, your Employee.ManagerId property should return an identifier that allows you to get a Manager for this Employee .

This will run counter to the many “kindness” you get from the Entity Framework box, but this is usually the case for DDD. He recommended creating a model of your domain around a business domain, and not for your database.

Personally, I think that using EF objects as a model of my domain does not work well when I do DDD. Things like the lazy properties of navigation navigation are contrary to the good practice of DDD. These days, I usually use document databases in my own projects, but when I have to use SQL, I limit my EF objects to my persistence level and encode my repositories to return non-EF objects from my domain model.

+4
source

Assuming you have the usual setup, where your application uses one DbContext:

Yes, it will also save the anchored object.

You are currently setting the manager name, it downloads the manager link and tracks it. When you save the changes by calling DbContext.SaveChanges , it will make all the changes made to the objects that DbContext monitors the disconnect.

The only possibility not to have this behavior is to use multiple instances of DbContext , but this opens up many other problems (for example: they do not know about each other's changes).

+1
source

Source: https://habr.com/ru/post/1213914/


All Articles