DDD and EF Core: Preserving encapsulation

 


The whole point of Encapsulation and Separation of concerns is to reduce complexity

The more coupling leads to an exponential growth of complexity



With separation of concerns we can maintain the same number of elements but reduce the coupling or connections between them.





Public setters in domain classes is a red flag.  Setters prevent the class from maintaining invariants because this  class has no control over how its clients use those setters.  
Always make property setters in domain classes private by default.

Proper way to set up many-to-one relationships with EF Core with private constructor and reference to a the FavouriteCourse model:
   



And with the mappings:

The query to select the join:



To reduce complexity and bugs, always load all entities whether they are required or not.  This is called Eager loading of relationships. 





To add Lazy Loading, you need to add the following 




Avoid the use of explicit lazy loaders such as this:




Db Context implements the identity map pattern whereby the Find method checks the local cache before retrieving from the database. Cache only works within the db context instance.  Find is the only method that will read from the cache.  Although Linq methods such as SingleOrDefault will write to the cache, only Find will write and read to and from the cache.  Only use Linq methods when you need to retrieve more than one entity at once.  It will even refer to the same object in memory so which is referential equality. 




This requires a Base Entity class which should be inherited by all Entity classes.  Optional to add type if Ids are different types.
Domain class implements Entity class and Id is removed.





Comments

Popular posts from this blog

Microservices and Service-Oriented Architecture

Version control and Continuous Integration/Continuous Deployment (CI/CD)

Principles of Clean Code