Entity Framework Core 11 and Complex Types
One of the most interesting challenges in software development is finding the balance between an expressive domain model and the limitations of the technologies used to persist data.
Anyone who has worked with Domain-Driven Design (DDD) for some time has probably had to adapt a domain model to accommodate the peculiarities of an ORM. In some situations, we create auxiliary properties, implement custom converters, or modify a class structure simply because the persistence mechanism cannot represent it adequately.
While these solutions are perfectly legitimate, they introduce complexity that does not necessarily belong to the problem we are trying to solve.
With the release of Entity Framework Core 11, some of the distance between the domain model and the persistence model has narrowed. Complex Types have received significant improvements, including the ability to use their nested properties as primary keys, alternate keys, and indexes.
Beyond learning about a new framework feature, it is worth understanding how this evolution influences our modeling and architectural decisions.
Entities and Value Objects: Understanding the Difference
Before exploring EF Core's capabilities, we need to revisit two fundamental concepts of DDD: Entities and Value Objects.
An Entity is characterized by its identity. A customer remains the same customer regardless of changes to their name, address, or phone number. Their attributes may change over time, but their identity remains.
A Value Object, on the other hand, is defined by the values it represents. Two addresses with identical attributes can be considered equivalent within a given context. We do not necessarily need to assign an individual identity to each of them.
The same reasoning applies to monetary values, geographic coordinates, validity periods, and document identifiers.
Consider the following representation:
public sealed record Address( string Street, string City, string State, string PostalCode); By using a record, we benefit from the structural equality implementation provided by C#.
var first = new Address( "100 Main Street", "Seattle", "WA", "98101"); var second = new Address( "100 Main Street", "Seattle", "WA", "98101"); Console.WriteLine(first == second); // True Of course, using a record does not automatically turn an object into a well-designed Value Object. We still need to consider its invariants, immutability, and meaning within the domain.
The language provides mechanisms for implementing the concept, but the domain determines its semantics.
This distinction matters because not every structured object needs to be treated as an entity by the persistence mechanism.
The Evolution of Complex Types in Entity Framework
For a long time, one of the primary approaches to representing Value Objects in Entity Framework Core was through Owned Entity Types, configured using the OwnsOne() method.
builder.OwnsOne(customer => customer.Address); Although this works in many scenarios, an Owned Type is still internally treated by EF Core as a dependent entity type, with its own identity and tracking rules.
This introduces a conceptual difference between what we intend to represent in the domain and how the ORM interprets the object.
Complex Types, introduced in EF Core 8, emerged as an alternative more closely aligned with value semantics. Unlike Owned Types, they do not have an independent identity within the Entity Framework model.
EF Core 10 expanded this support by introducing JSON mapping and optional Complex Types. EF Core 11 continues this evolution, improving support for inheritance mapping strategies, keys, indexes, and nested property configuration.
We can configure our address as a Complex Type:
builder.ComplexProperty(customer => customer.Address); In a relational database, using conventional column mapping, the address can be persisted within the customer table itself.
CREATE TABLE Customers ( Id UNIQUEIDENTIFIER NOT NULL PRIMARY KEY, Name NVARCHAR(150) NOT NULL, Address_Street NVARCHAR(200) NOT NULL, Address_City NVARCHAR(100) NOT NULL, Address_State NVARCHAR(2) NOT NULL, Address_PostalCode NVARCHAR(10) NOT NULL ); The SQL shown here is illustrative, but it demonstrates an important characteristic: we can maintain a structured domain model without necessarily increasing the number of database tables or relationships.
The object-oriented structure and the relational structure do not need to be identical.
A More Expressive Fluent API
One of the improvements introduced in EF Core 11 concerns the configuration of nested properties within Complex Types.
Previously, we could configure the maximum length of a property using an approach similar to this:
builder.ComplexProperty(customer => customer.Address) .Property(address => address.PostalCode) .HasMaxLength(10); With EF Core 11, we can access the nested property directly through an expression:
builder.Property(customer => customer.Address.PostalCode) .HasMaxLength(10); This configuration assumes that Address has already been recognized or explicitly configured as a Complex Type.
At first glance, this may seem like nothing more than a syntactic improvement. However, in extensive domain models with multiple levels of composition, it makes persistence configurations easier to read.
The Fluent API follows the structure of the object we are modeling more naturally.
This does not eliminate the need to configure mappings carefully, but it reduces some of the accidental complexity within the infrastructure layer.
Primitive Obsession: When Primitive Types Say Too Little
Imagine a financial application that manages customers, bank accounts, and loan agreements.
A traditional implementation might represent every identifier using a Guid:
public Task TransferAsync( Guid sourceAccountId, Guid destinationAccountId, decimal amount); The code works. However, as far as the compiler is concerned, a bank account identifier has exactly the same type as a customer or loan identifier.
Nothing prevents someone from writing:
await TransferAsync( customerId, destinationAccountId, 500m); The compiler accepts the call, even though it is semantically incorrect.
This problem is associated with a code smell known as Primitive Obsession, characterized by the excessive use of primitive types to represent concepts that have specific meanings within the domain.
An alternative is to use Strongly Typed IDs.
public readonly record struct CustomerId(Guid Value); public readonly record struct BankAccountId(Guid Value); public readonly record struct LoanId(Guid Value); We can now change the operation's signature:
public Task TransferAsync( BankAccountId sourceAccountId, BankAccountId destinationAccountId, decimal amount); Attempting to pass a CustomerId now results in a compilation error.
We have effectively moved an entire category of potential runtime errors to compile time.
Beyond type safety, the code communicates its intent more clearly. We are no longer manipulating generic identifiers, but meaningful business concepts.
Strongly Typed IDs Before EF Core 11
Strongly Typed IDs are not a feature introduced by EF Core 11. Previous versions already supported them through Value Converters.
Consider the following configuration:
builder.HasKey(customer => customer.Id); builder.Property(customer => customer.Id) .HasConversion( id => id.Value, value => new CustomerId(value)); The Value Converter establishes a transformation between the type used by the domain and the type stored in the database.
Within the domain, the property remains a CustomerId. In the database, it is stored as a Guid.
This approach is mature, relatively straightforward, and remains an excellent alternative.
However, from a mapping perspective, the converter treats the object as a single value. Its internal properties are not individually represented in the persistence model.
This limitation becomes more relevant when dealing with composite objects, particularly when their properties need to participate in queries, keys, or indexes.
This is precisely where the new capabilities of EF Core 11 become interesting.
Primary Keys Within Complex Types
Starting with EF Core 11, we can use scalar properties within non-collection Complex Types as part of an entity's key.
Consider our identifier:
public readonly record struct CustomerId(Guid Value) { public static CustomerId New() => new(Guid.NewGuid()); } And a simplified entity:
public sealed class Customer { public CustomerId Id { get; private set; } public string Name { get; private set; } = null!; public Address Address { get; private set; } = null!; private Customer() { } public Customer( CustomerId id, string name, Address address) { if (id.Value == Guid.Empty) throw new ArgumentException("Invalid customer ID."); Id = id; Name = name; Address = address; } } The mapping can be configured as follows:
public sealed class CustomerConfiguration : IEntityTypeConfiguration<Customer> { public void Configure( EntityTypeBuilder<Customer> builder) { builder.ComplexProperty(customer => customer.Id); builder.HasKey(customer => customer.Id.Value); builder.Property(customer => customer.Id.Value) .HasColumnName("Id") .ValueGeneratedNever(); builder.Property(customer => customer.Name) .HasMaxLength(150) .IsRequired(); builder.ComplexProperty(customer => customer.Address); } } The fundamental difference lies in the key declaration:
builder.HasKey(customer => customer.Id.Value); Entity Framework recognizes the nested Value property as the entity's primary key.
It is important to understand that we are not assigning an identity to the Complex Type. The identity still belongs to the Customer entity. The Complex Type simply encapsulates the value used to represent that identity.
Since we have chosen to generate identifiers within the application, we use ValueGeneratedNever() to make that decision explicit.
It is also worth remembering that a record struct can be initialized with its default value. Type safety does not replace domain invariant validation, which is why the example explicitly verifies that the identifier is valid.
When the Domain Itself Has a Composite Identity
The benefits of this functionality become even more apparent when working with composite identifiers.
Imagine a multi-tenant system in which a customer is identified by the combination of the organization they belong to and their individual identifier.
public readonly record struct CustomerIdentity( Guid TenantId, Guid CustomerId); Instead of spreading these two properties across the entity, we can encapsulate them within a single domain concept.
The composite key configuration reflects that structure:
builder.ComplexProperty(customer => customer.Identity); builder.HasKey(customer => new { customer.Identity.TenantId, customer.Identity.CustomerId }); The model communicates that both values, together, represent an identity.
At the database level, we still use a conventional composite primary key.
This approach can be useful in multi-tenant systems, financial platforms, and integrations with legacy systems that rely on composite identifiers.
However, including the tenant identifier in the primary key does not guarantee isolation between organizations. We still need appropriate authorization mechanisms, filtering, access controls, and, depending on the architecture, security policies within the database itself.
Good modeling contributes to security, but it does not replace a security architecture.
Indexing Value Object Properties
Another relevant improvement is the ability to create indexes directly on nested properties within Complex Types.
Imagine that we frequently need to retrieve customers from a particular ZIP code:
builder.HasIndex(customer => customer.Address.PostalCode); We can also create composite indexes involving properties within Complex Types:
builder.HasIndex(customer => new { customer.Address.State, customer.Address.City }); This allows database optimization decisions to be implemented without forcing the domain model to abandon its structure.
A LINQ query can continue to express the application's intent naturally:
var customers = await context.Customers .AsNoTracking() .Where(customer => customer.Address.State == "WA" && customer.Address.City == "Seattle") .ToListAsync(); Entity Framework translates access to the nested properties into their corresponding database columns.
Naturally, the existence of an index does not guarantee that the database will use it. Selectivity, data distribution, column order, and query characteristics continue to influence the execution plan.
A more expressive ORM does not eliminate the need to understand relational databases.
Complex Types, JSON, and LINQ Queries
Another interesting possibility is persisting a Value Object as a JSON document.
builder.ComplexProperty( customer => customer.Address, address => address.ToJson()); Introduced for Complex Types in EF Core 10, this capability received additional configuration options in EF Core 11, including support for indexing nested JSON paths when supported by the database provider.
The domain remains virtually unchanged, while the infrastructure can adopt a different physical representation.
This can be particularly useful for highly cohesive structures, configuration settings, preferences, or supplementary information within an aggregate.
Improvements in LINQ translation also complement this evolution. EF Core 11 introduces support for operations such as MaxByAsync() and MinByAsync(), while improving the translation of grouping operations and eliminating certain redundant SQL conversions.
Together, these capabilities make querying structured models more natural without unnecessarily materializing data in memory.
However, storing an object as JSON is not inherently better than using relational columns. We must consider access patterns, constraint requirements, available indexing capabilities, database portability, and maintenance costs.
The decision should be driven by application requirements rather than simply by the availability of a new API.
Complex Types or Value Converters?
With the new features introduced in EF Core 11, would it be reasonable to conclude that we should replace every Value Converter with a Complex Type?
Not necessarily.
If an identifier encapsulates only a Guid, a Value Converter may remain the simplest alternative. It has an established track record and adequately represents a transformation between two types.
When dealing with composite objects, properties that need to be queried individually, or components that participate in keys and indexes, Complex Types offer a more expressive representation.
Owned Types also remain useful, particularly when modeling dependent elements that require their own identity or relationships within the persistence model.
The choice should consider the semantics of the object, persistence requirements, and the capabilities offered by the database provider.
In existing applications, any migration between these strategies should be accompanied by a review of the generated migrations, schema validation, and integration tests against the actual database.
We should not assume that a mapping change will be transparent simply because the domain model remains unchanged.
Architecture is not about adopting every new feature. It is about understanding when a feature provides enough value to justify its adoption.
The Impact on Software Architecture
The most interesting aspect of these improvements is not exclusively about the new APIs.
It lies in the ability to build models that better express business rules and concepts without introducing unnecessary adaptations to satisfy the persistence mechanism.
In a domain-centric architecture, we can keep Value Objects, entities, invariants, and Strongly Typed IDs within the domain layer, while the infrastructure layer remains responsible for Entity Framework configuration.
This separation helps reduce coupling, improves testability, and makes the model easier to evolve.
That does not mean the domain is completely isolated from every consequence of persistence. Decisions regarding consistency, concurrency, transactions, and aggregate boundaries still require an understanding of infrastructure characteristics.
Technology independence is an architectural direction, not an absolute guarantee.
The goal is to prevent implementation details from becoming more prominent than the business problem itself.
A framework should support architectural decisions, not dictate them.
Final Thoughts
The evolution of Complex Types in Entity Framework Core 11 represents an important step toward bringing domain modeling and data persistence closer together.
The ability to use nested properties as keys and indexes, simplify configurations, and work with Strongly Typed IDs expands our implementation options without requiring us to abandon fundamental DDD concepts.
However, none of these features replaces good modeling.
Using ComplexProperty(), records, or Strongly Typed IDs does not automatically make an application domain-driven. What matters is our ability to understand the problem, represent its concepts, protect its invariants, and establish coherent responsibilities.
Frameworks evolve. Databases evolve. Programming languages evolve.
The fundamentals of software engineering remain.
And perhaps that is one of the most meaningful contributions of EF Core 11: allowing us to spend less time adapting our domain to technology and more time understanding what we actually need to model.
References and Further Reading
For a deeper understanding of the conceptual foundations, I recommend Domain-Driven Design: Tackling Complexity in the Heart of Software by Eric Evans, Implementing Domain-Driven Design and Domain-Driven Design Distilled by Vaughn Vernon, and Refactoring: Improving the Design of Existing Code by Martin Fowler.
For implementation details, Microsoft's official documentation is an excellent starting point:
Breaking Changes in EF Core 11
原文:https://www.a8q9.cn/en/article/entity-framework-core-11-and-complex-types-4c9d84.html