DbContext Class https://learn.microsoft.com/dotnet/api/microsoft.entityframeworkcore.dbcontext
•
Compare EF Core & EF6.x https://learn.microsoft.com/ef/efcore-and-ef6/index
Infrastructure in Entity Framework Core from a DDD perspective From a DDD point of view, an important capability of EF is the ability to use POCO domain entities,
also known in EF terminology as POCO
code-first entities . If you use POCO domain entities, your
domain model classes are persistence-ignorant, following the
Persistence Ignorance
and the
Infrastructure Ignorance
principles.
Per DDD patterns, you should encapsulate domain behavior and rules within the entity class itself, so
it can control invariants, validations, and rules when accessing any collection. Therefore, it is not a
good practice in DDD to allow public access to collections of child entities or value objects. Instead,
you want to expose methods that control how and when your fields and property collections can be
updated, and what behavior and actions should occur when that happens.
Since EF Core 1.1, to satisfy those DDD requirements, you can have plain fields in your entities instead
of public properties. If you do not want an entity field to be externally accessible, you can just create
the attribute or field instead of a property. You can also use private property setters.
In a similar way, you can now have read-only access to collections by using a public property typed as
IReadOnlyCollection , which is backed by a private field member for the collection (like a
List ) in your entity that relies on EF for persistence. Previous versions of Entity Framework
required collection properties to support
ICollection , which meant that any developer using the
parent entity class could add or remove items through its property collections. That possibility would
be against the recommended patterns in DDD.
246
CHAPTER 6 | Tackle Business Complexity in a Microservice with DDD and CQRS Patterns
You can use a private collection while exposing a read-only
IReadOnlyCollection object, as
shown in the following code example: