| title | Immutable Domain Models in Encina |
|---|---|
| layout | default |
| parent | Features |
This guide explains how to use immutable domain entities (C# records) with EF Core while preserving domain events. Immutability is a powerful pattern for Domain-Driven Design, ensuring entities cannot be modified after creation except through explicit state transitions.
- Overview
- The Problem
- The Solution
- Quick Start
- API Reference
- Best Practices
- Integration with EF Core
- Immutable Updates with Unit of Work Pattern
- Immutable Updates with IFunctionalRepository
- Non-EF Core Provider Workflow
- Provider Support Comparison
- Testing
- FAQ
Immutable entities provide several benefits:
| Benefit | Description |
|---|---|
| Thread Safety | No mutable state means no race conditions |
| Predictability | State changes are explicit and traceable |
| Testing | Easier to reason about and test |
| Event Sourcing Ready | Natural fit for event-driven architectures |
| Audit Trail | State transitions through methods leave clear audit points |
In DDD, aggregate roots should enforce invariants and control all state changes. With immutable records, state changes are explicit:
// Mutable (traditional) - state changes hidden
order.Status = OrderStatus.Shipped; // Where did this happen? Who authorized it?
// Immutable - state changes explicit
var shippedOrder = order.Ship(); // Clear intent, domain event raisedWhen using C# records with EF Core, you face two challenges:
EF Core tracks entity instances by reference. When you use a with-expression, you create a new instance:
var order = await context.Orders.FindAsync(orderId);
var modifiedOrder = order with { Status = OrderStatus.Shipped }; // New instance!
// EF Core still tracks 'order', not 'modifiedOrder'
// SaveChanges won't persist the changes correctlyDomain events raised during state transitions are lost when creating new instances:
public record Order : AggregateRoot<OrderId>
{
public Order Ship()
{
AddDomainEvent(new OrderShippedEvent(Id)); // Event on 'this'
return this with { Status = OrderStatus.Shipped }; // New instance without events!
}
}Encina provides two complementary utilities:
Copies domain events from the original instance to the new instance:
var shippedOrder = order.Ship().WithPreservedEvents(order);
// shippedOrder now has the OrderShippedEventHandles the detach/attach pattern with automatic event preservation:
var result = context.UpdateImmutable(shippedOrder);
// - Detaches original tracked entity
// - Attaches modified entity
// - Marks as Modified
// - Copies events (if both are IAggregateRoot)flowchart TD
subgraph Step1["1. Load Entity"]
OrderTracked["order (tracked)<br/>Status: Pending<br/>Events: [ ]<br/>EF Core Change Tracker"]
end
subgraph Step2["2. State Transition (with-expression)"]
OrderOriginal["order<br/>Status: Pending<br/>Events: [ ]"]
ShippedNew["shippedOrder (new instance)<br/>Status: Shipped<br/>Events: [Event]<br/>Event raised here"]
OrderOriginal --> ShippedNew
end
subgraph Step3["3. WithPreservedEvents (optional)"]
ShippedPreserved["shippedOrder<br/>Status: Shipped<br/>Events: [Event]<br/>Events copied from original if needed"]
end
subgraph Step4["4. UpdateImmutable"]
OrderDetached["order<br/>State: Detached"]
ShippedModified["shippedOrder<br/>State: Modified<br/>Now tracked"]
end
subgraph Step5["5. SaveChanges"]
Dispatched["Events Dispatched"]
end
Step1 --> Step2
Step2 --> Step3
Step3 --> Step4
Step4 --> Step5
using Encina.DomainModeling;
public record Order : AggregateRoot<Guid>
{
public required string CustomerName { get; init; }
public required OrderStatus Status { get; init; }
public required decimal Total { get; init; }
// State transition with domain event
public Order Ship()
{
if (Status != OrderStatus.Confirmed)
throw new InvalidOperationException("Only confirmed orders can be shipped");
AddDomainEvent(new OrderShippedEvent(Id, DateTime.UtcNow));
return this with { Status = OrderStatus.Shipped };
}
public Order Cancel(string reason)
{
if (Status == OrderStatus.Shipped)
throw new InvalidOperationException("Cannot cancel shipped orders");
AddDomainEvent(new OrderCancelledEvent(Id, reason));
return this with { Status = OrderStatus.Cancelled };
}
}public class OrdersDbContext : DbContext
{
public DbSet<Order> Orders => Set<Order>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Order>(entity =>
{
entity.HasKey(e => e.Id);
entity.Property(e => e.CustomerName).HasMaxLength(200).IsRequired();
entity.Property(e => e.Status).HasConversion<string>();
entity.Property(e => e.Total).HasPrecision(18, 2);
});
}
}using Encina.EntityFrameworkCore.Extensions;
public class ShipOrderHandler : ICommandHandler<ShipOrderCommand, Unit>
{
private readonly OrdersDbContext _context;
public async ValueTask<Either<EncinaError, Unit>> Handle(
ShipOrderCommand command,
IRequestContext ctx,
CancellationToken ct)
{
var order = await _context.Orders.FindAsync([command.OrderId], ct);
if (order is null)
return EncinaError.NotFound($"Order {command.OrderId} not found");
// State transition - returns new instance with event
var shippedOrder = order.Ship().WithPreservedEvents(order);
// Update change tracker with event preservation
var result = _context.UpdateImmutable(shippedOrder);
return await result.MatchAsync(
Left: error => error,
Right: async _ =>
{
await _context.SaveChangesAsync(ct);
return unit;
});
}
}Copies domain events from the original instance to the new instance.
public static TAggregateRoot WithPreservedEvents<TAggregateRoot>(
this TAggregateRoot newInstance,
TAggregateRoot originalInstance)
where TAggregateRoot : class, IAggregateRootParameters:
| Parameter | Description |
|---|---|
newInstance |
The new instance created from a with-expression |
originalInstance |
The original instance containing domain events |
Returns: The new instance with events copied, for fluent chaining.
Example:
var shippedOrder = order.Ship().WithPreservedEvents(order);Updates an immutable entity in the change tracker.
public static Either<EncinaError, Unit> UpdateImmutable<TEntity>(
this DbContext context,
TEntity modified)
where TEntity : classParameters:
| Parameter | Description |
|---|---|
context |
The DbContext containing the entity |
modified |
The modified entity instance to track |
Returns: Either<EncinaError, Unit> where Right indicates success.
Error Cases:
| Error Code | Description |
|---|---|
ENTITY_NOT_TRACKED |
Original entity not found in change tracker |
UPDATE_FAILED |
Detach/attach operation failed |
Example:
var result = context.UpdateImmutable(modifiedOrder);
result.Match(
Right: _ => Console.WriteLine("Success"),
Left: error => Console.WriteLine($"Failed: {error.Code}"));Async overload for API consistency.
public static Task<Either<EncinaError, Unit>> UpdateImmutableAsync<TEntity>(
this DbContext context,
TEntity modified,
CancellationToken cancellationToken = default)
where TEntity : classDomain events should be raised before the with-expression:
// Correct: Event raised before with-expression
public Order Ship()
{
AddDomainEvent(new OrderShippedEvent(Id)); // Event on 'this'
return this with { Status = OrderStatus.Shipped };
}
// Wrong: Event on new instance (lost without WithPreservedEvents)
public Order Ship()
{
var shipped = this with { Status = OrderStatus.Shipped };
shipped.AddDomainEvent(new OrderShippedEvent(Id)); // Event on new instance
return shipped;
}If your state transition methods raise events, always use WithPreservedEvents:
// When the method raises events
var shippedOrder = order.Ship().WithPreservedEvents(order);
// When just using with-expression (no events in method)
var renamedOrder = order with { CustomerName = "New Name" };
var result = context.UpdateImmutable(renamedOrder); // Copies events automaticallyEncapsulate all state changes in aggregate methods:
// Good: State change through aggregate method
var confirmedOrder = order.Confirm();
// Bad: Direct property modification (breaks encapsulation)
var confirmedOrder = order with { Status = OrderStatus.Confirmed };Enforce invariants before creating new instances:
public Order Ship()
{
// Guard clause first
if (Status != OrderStatus.Confirmed)
throw new InvalidOperationException("Only confirmed orders can be shipped");
if (Items.Count == 0)
throw new InvalidOperationException("Cannot ship empty order");
AddDomainEvent(new OrderShippedEvent(Id));
return this with { Status = OrderStatus.Shipped };
}For ROP-style validation:
public Either<OrderError, Order> Ship()
{
if (Status != OrderStatus.Confirmed)
return OrderError.InvalidStatusTransition(Status, OrderStatus.Shipped);
AddDomainEvent(new OrderShippedEvent(Id));
return this with { Status = OrderStatus.Shipped };
}
// Usage
var result = order.Ship()
.Map(shipped => shipped.WithPreservedEvents(order));For automatic event dispatch after SaveChanges, configure the domain event dispatcher:
services.AddEncinaEntityFrameworkCore<OrdersDbContext>(config =>
{
config.UseDomainEvents = true; // Enables DomainEventDispatcherInterceptor
});The interceptor automatically:
- Collects events from tracked aggregate roots before SaveChanges
- Dispatches events after SaveChanges succeeds
- Handles both sync and async SaveChanges
Combine immutable updates with row versioning:
public record Order : AggregateRoot<Guid>, IConcurrencyAware
{
public byte[] RowVersion { get; init; } = [];
// ... other properties
}
// EF Core configuration
modelBuilder.Entity<Order>()
.Property(e => e.RowVersion)
.IsRowVersion();When using IUnitOfWork, Encina provides a clean API for updating immutable aggregates:
public class ShipOrderHandler : ICommandHandler<ShipOrderCommand, Unit>
{
private readonly IUnitOfWork _unitOfWork;
public async ValueTask<Either<EncinaError, Unit>> Handle(
ShipOrderCommand command,
IRequestContext ctx,
CancellationToken ct)
{
await using (_unitOfWork)
{
var repository = _unitOfWork.Repository<Order, Guid>();
var orderResult = await repository.GetByIdAsync(command.OrderId, ct);
return await orderResult.MatchAsync(
Left: error => error,
Right: async order =>
{
// 1. Perform domain operation
var shippedOrder = order.Ship().WithPreservedEvents(order);
// 2. Use UpdateImmutable - handles change tracking automatically
var updateResult = _unitOfWork.UpdateImmutable(shippedOrder);
return await updateResult.MatchAsync(
Left: error => error,
Right: async _ =>
{
// 3. Commit changes - events dispatched automatically
await _unitOfWork.SaveChangesAsync(ct);
return Unit.Default;
});
});
}
}
}// Synchronous update
Either<EncinaError, Unit> UpdateImmutable<TEntity>(TEntity modified)
where TEntity : class, IAggregateRoot;
// Asynchronous update
ValueTask<Either<EncinaError, Unit>> UpdateImmutableAsync<TEntity>(
TEntity modified,
CancellationToken cancellationToken = default)
where TEntity : class, IAggregateRoot;Returns: Either<EncinaError, Unit> where:
Right(Unit.Default)- SuccessLeft(RepositoryErrors.EntityNotTracked)- Original entity not found in change trackerLeft(RepositoryErrors.UpdateFailed)- Detach/attach operation failed
public async ValueTask<Either<EncinaError, Unit>> TransferOrderOwnership(
Guid orderId,
Guid newOwnerId,
CancellationToken ct)
{
await using (_unitOfWork)
{
var orderRepo = _unitOfWork.Repository<Order, Guid>();
var customerRepo = _unitOfWork.Repository<Customer, Guid>();
// Load both entities
var orderResult = await orderRepo.GetByIdAsync(orderId, ct);
var customerResult = await customerRepo.GetByIdAsync(newOwnerId, ct);
return await (orderResult, customerResult).Apply((order, customer) =>
{
// Domain operations
var updatedOrder = order.TransferTo(customer.Id)
.WithPreservedEvents(order);
// Update immutable aggregate
return _unitOfWork.UpdateImmutable(updatedOrder)
.BindAsync(_ => _unitOfWork.SaveChangesAsync(ct));
});
}
}IFunctionalRepository<TEntity, TId> also supports immutable updates through UpdateImmutableAsync:
public class UpdateOrderStatusHandler : ICommandHandler<UpdateOrderStatusCommand, Unit>
{
private readonly IFunctionalRepository<Order, Guid> _repository;
private readonly IUnitOfWork _unitOfWork;
public async ValueTask<Either<EncinaError, Unit>> Handle(
UpdateOrderStatusCommand command,
IRequestContext ctx,
CancellationToken ct)
{
return await _repository.GetByIdAsync(command.OrderId, ct)
.BindAsync(async order =>
{
var modifiedOrder = order.UpdateStatus(command.NewStatus)
.WithPreservedEvents(order);
return await _repository.UpdateImmutableAsync(modifiedOrder, ct);
})
.BindAsync(_ => _unitOfWork.SaveChangesAsync(ct));
}
}ValueTask<Either<EncinaError, Unit>> UpdateImmutableAsync(
TEntity modified,
CancellationToken cancellationToken = default);Using IFunctionalRepository for immutable updates provides:
| Benefit | Description |
|---|---|
| Consistency | Same API across EF Core repositories |
| Encapsulation | Aggregate-specific update logic stays in one place |
| Testability | Easy to mock UpdateImmutableAsync in unit tests |
| ROP Integration | Returns Either<EncinaError, Unit> for explicit error handling |
For providers without change tracking (Dapper, ADO.NET, MongoDB), use ImmutableAggregateHelper:
Non-EF Core providers lack automatic change tracking. When you update an immutable aggregate:
- Domain events on the original instance need to be manually copied
- The modified aggregate needs to be registered for event dispatch
- There's no "detach/attach" pattern needed
public class ShipOrderHandler : ICommandHandler<ShipOrderCommand, Unit>
{
private readonly IFunctionalRepository<Order, Guid> _repository;
private readonly IDomainEventCollector _eventCollector;
private readonly DomainEventDispatchHelper _dispatchHelper;
public async ValueTask<Either<EncinaError, Unit>> Handle(
ShipOrderCommand command,
IRequestContext context,
CancellationToken ct)
{
// 1. Load the order
var orderResult = await _repository.GetByIdAsync(command.OrderId, ct);
return await orderResult.MatchAsync(
Left: error => error,
Right: async order =>
{
// 2. Perform domain operation (raises event, returns new instance)
var shippedOrder = order.Ship();
// 3. Prepare for update (copies events, tracks aggregate)
ImmutableAggregateHelper.PrepareForUpdate(
shippedOrder,
order,
_eventCollector);
// 4. Persist changes
var updateResult = await _repository.UpdateAsync(shippedOrder, ct);
// 5. Dispatch domain events
if (updateResult.IsRight)
await _dispatchHelper.DispatchCollectedEventsAsync(ct);
return updateResult.Map(_ => Unit.Default);
});
}
}public static TAggregate PrepareForUpdate<TAggregate>(
TAggregate modified,
TAggregate original,
IDomainEventCollector collector)
where TAggregate : class, IAggregateRootWhat it does:
- Copies events: Calls
modified.CopyEventsFrom(original)to preserve domain events - Tracks aggregate: Calls
collector.TrackAggregate(modified)for event dispatch - Returns modified: Returns the modified aggregate for fluent chaining
Parameters:
| Parameter | Description |
|---|---|
modified |
The new aggregate instance created via with-expression |
original |
The original aggregate containing domain events |
collector |
The IDomainEventCollector for tracking and dispatch |
Register these services when using non-EF Core providers:
services.AddScoped<IDomainEventCollector, DomainEventCollector>();
services.AddScoped<DomainEventDispatchHelper>();// Compact fluent style
var preparedOrder = ImmutableAggregateHelper.PrepareForUpdate(
order.Ship(),
order,
_eventCollector);
await _repository.UpdateAsync(preparedOrder, ct);
await _dispatchHelper.DispatchCollectedEventsAsync(ct);| Provider | Change Tracking | UpdateImmutable Support | Helper Required |
|---|---|---|---|
| EF Core | Yes | IUnitOfWork.UpdateImmutable() |
None |
| EF Core | Yes | IFunctionalRepository.UpdateImmutableAsync() |
None |
| EF Core | Yes | DbContext.UpdateImmutable() |
None |
| Dapper | No | Returns OperationNotSupported |
ImmutableAggregateHelper |
| ADO.NET | No | Returns OperationNotSupported |
ImmutableAggregateHelper |
| MongoDB | No | Returns OperationNotSupported |
ImmutableAggregateHelper |
Non-EF providers return RepositoryErrors.OperationNotSupported from UpdateImmutableAsync:
var result = await dapperRepository.UpdateImmutableAsync(modified, ct);
result.Match(
Left: error =>
{
if (error.Code == "REPO_OPERATION_NOT_SUPPORTED")
{
// Use ImmutableAggregateHelper instead
ImmutableAggregateHelper.PrepareForUpdate(modified, original, collector);
// ... proceed with manual update
}
},
Right: _ => { /* Success */ });flowchart TD
A[Immutable Aggregate Update] --> B{Provider Type?}
B -->|EF Core| C[Use UpdateImmutable/UpdateImmutableAsync]
B -->|Dapper/ADO.NET/MongoDB| D[Use ImmutableAggregateHelper]
C --> E[Automatic event copy & tracking]
D --> F[Manual PrepareForUpdate call]
E --> G[SaveChangesAsync dispatches events]
F --> H[Manual DispatchCollectedEventsAsync]
[Fact]
public void Ship_ConfirmedOrder_ReturnsShippedOrderWithEvent()
{
// Arrange
var order = new Order(Guid.NewGuid())
{
CustomerName = "Test",
Status = OrderStatus.Confirmed,
Total = 100m
};
// Act
var shippedOrder = order.Ship().WithPreservedEvents(order);
// Assert
shippedOrder.Status.ShouldBe(OrderStatus.Shipped);
shippedOrder.DomainEvents.Count.ShouldBe(1);
shippedOrder.DomainEvents[0].ShouldBeOfType<OrderShippedEvent>();
}[Fact]
public async Task UpdateImmutable_ModifiedEntity_PersistsChanges()
{
// Arrange
await using var context = CreateDbContext();
var order = new Order(Guid.NewGuid())
{
CustomerName = "Test",
Status = OrderStatus.Pending,
Total = 100m
};
context.Orders.Add(order);
await context.SaveChangesAsync();
// Act
var modifiedOrder = order with { Status = OrderStatus.Confirmed };
var result = context.UpdateImmutable(modifiedOrder);
await context.SaveChangesAsync();
// Assert
result.IsRight.ShouldBeTrue();
await using var verifyContext = CreateDbContext();
var stored = await verifyContext.Orders.FindAsync(order.Id);
stored!.Status.ShouldBe(OrderStatus.Confirmed);
}Use immutable entities when:
- You want explicit, auditable state transitions
- Thread safety is important
- You're preparing for event sourcing
- Your domain model benefits from functional programming patterns
Yes, but records provide better ergonomics with the with-expression. For classes, you'd need to implement cloning manually.
UpdateImmutable automatically copies events from the original tracked entity to the modified entity. WithPreservedEvents is only needed when you raise events in the state transition method and want them on the new instance before calling UpdateImmutable.
No, UpdateImmutable requires the original entity to be tracked. For disconnected scenarios, attach the entity first:
context.Attach(entity);
var result = context.UpdateImmutable(modifiedEntity);IUnitOfWork has full support for immutable updates via UpdateImmutable() and UpdateImmutableAsync():
var order = await unitOfWork.Repository<Order, Guid>().GetByIdAsync(orderId);
var shipped = order.Ship().WithPreservedEvents(order);
// Use UpdateImmutable on the UnitOfWork
var result = unitOfWork.UpdateImmutable(shipped);
await unitOfWork.SaveChangesAsync();See Immutable Updates with Unit of Work Pattern for complete documentation.
Non-EF Core providers don't have a change tracker. Use ImmutableAggregateHelper.PrepareForUpdate():
// 1. Load entity
var order = await repository.GetByIdAsync(orderId);
// 2. Create modified instance
var shipped = order.Ship();
// 3. PrepareForUpdate copies events and tracks aggregate
ImmutableAggregateHelper.PrepareForUpdate(shipped, order, eventCollector);
// 4. Update and dispatch events
await repository.UpdateAsync(shipped);
await dispatchHelper.DispatchCollectedEventsAsync();See Non-EF Core Provider Workflow for complete documentation.