Posts

Showing posts from March, 2024

DDD and EF Core: Preserving encapsulation

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

Unit of work

Image
  Unit of work is lower order abstraction to the repositories, so they should not appear in the unit of work.

Partially-initialized Entities Anti-pattern

Image
  Stop loading at aggregate boundaries

IQueryable and IEnumerable

Image
  The IQueryable interface is too broad.  Its intention is to allow any LINQ expression to be translated into SQL, which is an impossible task.  It is misleading to use the IQueryable interface as part of the public API.  It should be maintained within the repository and the list converted to IEnumerable.   The IQueryable interface therefore should not be used outside the repository. In the collections, IEnumerable is the most generic collection.  And the IReadOnlyList, Array and IList are the most specific.  We should always return IReadOnlyList when it comes to returning collections from public methods or properties.