Skip to content

Chronicle projections for optional nested objects

Use Nested() in a Cratis Chronicle projection when a read model has one optional object, such as an employee’s active contract or a task’s current assignee. Events update properties inside that object, and ClearWith<TEvent>() sets it to null when the relationship ends. Use children collections instead when the parent owns several items identified by keys.

Select the parent’s nullable property with Nested(), then declare the events that populate and clear it. In this example, a slice can have a command; setting or clearing that command changes the Command object without replacing the slice:

Nested object projection
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Projections;
[EventType]
public record SliceCreatedForNestedBasic(string Name);
[EventType]
public record CommandSetForDeclarativeNestedBasic(string Name, string Schema);
[EventType]
public record CommandClearedForDeclarativeNestedBasic;
public record SliceForNestedBasic(
string Name,
CommandItemForNestedBasic? Command);
public record CommandItemForNestedBasic(
string Name,
string Schema);
public class SliceProjectionForNestedBasic : IProjectionFor<SliceForNestedBasic>
{
public void Define(IProjectionBuilderFor<SliceForNestedBasic> builder) => builder
.From<SliceCreatedForNestedBasic>()
.Nested(m => m.Command, nested => nested
.From<CommandSetForDeclarativeNestedBasic>()
.ClearWith<CommandClearedForDeclarativeNestedBasic>());
}

View C# snippet source on GitHub

Declare the nested property as nullable so the model can represent both states: an object with values, or no object after a clear event:

Read model with nested object
public record SliceWithNestedCommand(
string Name,
CommandItemForNestedCommand? Command);
public record CommandItemForNestedCommand(
string Name,
string Schema);

View C# snippet source on GitHub

Use a set event to carry the nested values and a separate clear event to record that the object is no longer present:

Nested object events
using Cratis.Chronicle.Events;
[EventType]
public record SliceCreatedForNestedEvents(string Name);
[EventType]
public record CommandSetForNestedEvents(string Name, string Schema);
[EventType]
public record CommandClearedForNestedEvents;

View C# snippet source on GitHub

The set event populates Command on the parent. Later matching events update only the nested properties they map, leaving other properties unchanged. They do not replace the whole object.

The clear event sets Command to null. A later set event can populate it again. This lets the read model distinguish an absent command from a command whose properties happen to have default values.

Call From<TEvent>() multiple times to update the nested object from several event types:

Multiple nested events
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Projections;
[EventType]
public record SliceCreatedForNestedUpdates(string Name);
[EventType]
public record CommandSetForNestedUpdates(string Name, string Schema);
[EventType]
public record CommandRenamedForNestedUpdates(string NewName);
[EventType]
public record CommandSchemaUpdatedForNestedUpdates(string UpdatedSchema);
[EventType]
public record CommandClearedForNestedUpdates;
public record SliceForNestedUpdates(
string Name,
CommandItemForNestedUpdates? Command);
public record CommandItemForNestedUpdates(
string Name,
string Schema);
public class SliceProjectionForNestedUpdates : IProjectionFor<SliceForNestedUpdates>
{
public void Define(IProjectionBuilderFor<SliceForNestedUpdates> builder) => builder
.From<SliceCreatedForNestedUpdates>()
.Nested(m => m.Command, nested => nested
.From<CommandSetForNestedUpdates>()
.From<CommandRenamedForNestedUpdates>(b => b
.Set(m => m.Name).To(e => e.NewName))
.From<CommandSchemaUpdatedForNestedUpdates>(b => b
.Set(m => m.Schema).To(e => e.UpdatedSchema))
.ClearWith<CommandClearedForNestedUpdates>());
}

View C# snippet source on GitHub

The rename event updates Name, while the schema-update event updates Schema. Keeping those mappings separate preserves the other value when either event arrives.

The nested builder inherits the parent’s AutoMap setting. With AutoMap enabled, event properties map to matching properties on the nested object. Here an event carrying only Schema updates that property without clearing Name:

AutoMap in a nested scope
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Projections;
[EventType]
public record SliceCreatedForNestedAutoMap(string Name);
[EventType]
public record CommandSetForNestedAutoMap(string Name, string Schema);
[EventType]
public record CommandUpdatedForNestedAutoMap(string Schema);
[EventType]
public record CommandClearedForNestedAutoMap;
public record SliceForNestedAutoMap(
string Name,
CommandItemForNestedAutoMap? Command);
public record CommandItemForNestedAutoMap(
string Name,
string Schema);
public class SliceProjectionForNestedAutoMap : IProjectionFor<SliceForNestedAutoMap>
{
public void Define(IProjectionBuilderFor<SliceForNestedAutoMap> builder) => builder
.From<SliceCreatedForNestedAutoMap>()
.Nested(m => m.Command, nested => nested
.From<CommandSetForNestedAutoMap>()
.From<CommandUpdatedForNestedAutoMap>()
.ClearWith<CommandClearedForNestedAutoMap>());
}

View C# snippet source on GitHub

Declare a separate Nested() block for each optional object. Each block has its own event mappings and clear event:

Multiple nested objects
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Projections;
[EventType]
public record SliceCreatedWithMultipleNested(string Name);
[EventType]
public record CommandSetWithMultipleNested(string Name, string Schema);
[EventType]
public record CommandClearedWithMultipleNested;
[EventType]
public record ValidationConfiguredWithMultipleNested(string RuleName);
[EventType]
public record ValidationRemovedWithMultipleNested;
public record SliceWithMultipleNested(
string Name,
CommandItemWithMultipleNested? Command,
ValidationConfigWithMultipleNested? Validation);
public record CommandItemWithMultipleNested(
string Name,
string Schema);
public record ValidationConfigWithMultipleNested(
string RuleName);
public class SliceProjectionWithMultipleNested : IProjectionFor<SliceWithMultipleNested>
{
public void Define(IProjectionBuilderFor<SliceWithMultipleNested> builder) => builder
.From<SliceCreatedWithMultipleNested>()
.Nested(m => m.Command, nested => nested
.From<CommandSetWithMultipleNested>()
// A later CommandSetWithMultipleNested recreates Command after it is cleared.
.ClearWith<CommandClearedWithMultipleNested>())
.Nested(m => m.Validation, nested => nested
.From<ValidationConfiguredWithMultipleNested>()
.ClearWith<ValidationRemovedWithMultipleNested>());
}

MongoDB documents written by older versions may contain explicit null values for cleared nested objects. Property updates recreate a cleared nested object and repair legacy null parents, including those inside identifier-based array elements. This repair does not apply to positional (identifier-less) children or to adding a child ($push) under a null parent.

View C# snippet source on GitHub

Call Nested() inside a Children() builder when each child has its own optional object. Here each task has an optional assignee; the task key selects which child’s nested object to update:

Nested object in children
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Projections;
[EventType]
public record ProjectCreatedWithNestedChildren(string Name);
[EventType]
public record TaskAddedWithNestedChild(Guid TaskId, string Title);
[EventType]
public record TaskAssignedWithNestedChild(Guid TaskId, string Name, string Email);
[EventType]
public record TaskUnassignedWithNestedChild(Guid TaskId);
public record ProjectWithDeclarativeNestedChildren(
string Name,
IEnumerable<TaskWithNestedAssignee> Tasks);
public record TaskWithNestedAssignee(
Guid TaskId,
string Title,
AssigneeForNestedChild? Assignee);
public record AssigneeForNestedChild(
string Name,
string Email);
public class ProjectProjectionWithDeclarativeNestedChildren : IProjectionFor<ProjectWithDeclarativeNestedChildren>
{
public void Define(IProjectionBuilderFor<ProjectWithDeclarativeNestedChildren> builder) => builder
.From<ProjectCreatedWithNestedChildren>()
.Children(m => m.Tasks, tasks => tasks
.IdentifiedBy(m => m.TaskId)
.From<TaskAddedWithNestedChild>(b => b
.UsingKey(e => e.TaskId))
.Nested(m => m.Assignee, assignee => assignee
.From<TaskAssignedWithNestedChild>(b => b
.UsingKey(e => e.TaskId))
.ClearWith<TaskUnassignedWithNestedChild>()));
}

View C# snippet source on GitHub

Keep the employee in the read model when the contract ends. The contract’s clear event removes only the optional contract object:

Employee contract projection
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Projections;
[EventType]
public record EmployeeHiredWithNestedContract(string Name, string Department);
[EventType]
public record ContractStartedWithNestedContract(Guid ContractId, DateOnly StartDate, DateOnly EndDate, string Type);
[EventType]
public record ContractExtendedWithNestedContract(DateOnly NewEndDate);
[EventType]
public record ContractEndedWithNestedContract;
public record EmployeeWithNestedContract(
string Name,
string Department,
ContractForNestedEmployee? ActiveContract);
public record ContractForNestedEmployee(
Guid ContractId,
DateOnly StartDate,
DateOnly EndDate,
string Type);
public class EmployeeProjectionWithNestedContract : IProjectionFor<EmployeeWithNestedContract>
{
public void Define(IProjectionBuilderFor<EmployeeWithNestedContract> builder) => builder
.From<EmployeeHiredWithNestedContract>()
.Nested(m => m.ActiveContract, contract => contract
.From<ContractStartedWithNestedContract>()
.From<ContractExtendedWithNestedContract>(b => b
.Set(m => m.EndDate).To(e => e.NewEndDate))
.ClearWith<ContractEndedWithNestedContract>());
}

View C# snippet source on GitHub

Events:

Employee contract events
using Cratis.Chronicle.Events;
[EventType]
public record EmployeeHiredForNestedContractEvents(string Name, string Department);
[EventType]
public record ContractStartedForNestedContractEvents(Guid ContractId, DateOnly StartDate, DateOnly EndDate, string Type);
[EventType]
public record ContractExtendedForNestedContractEvents(DateOnly NewEndDate);
[EventType]
public record ContractEndedForNestedContractEvents;

View C# snippet source on GitHub

When a promotion-removed event arrives, clear the promotion without removing the product. A ValidUntil value alone does not trigger ClearWith; the declared clear event does:

Product promotion projection
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Projections;
[EventType]
public record ProductListedWithNestedPromotion(string Name, decimal BasePrice);
[EventType]
public record PromotionAppliedWithNestedPromotion(string Label, int DiscountPercent, DateTimeOffset ValidUntil);
[EventType]
public record PromotionRemovedWithNestedPromotion;
public record ProductWithNestedPromotion(
string Name,
decimal BasePrice,
PromotionForNestedProduct? Promotion);
public record PromotionForNestedProduct(
string Label,
int DiscountPercent,
DateTimeOffset ValidUntil);
public class ProductProjectionWithNestedPromotion : IProjectionFor<ProductWithNestedPromotion>
{
public void Define(IProjectionBuilderFor<ProductWithNestedPromotion> builder) => builder
.From<ProductListedWithNestedPromotion>()
.Nested(m => m.Promotion, promotion => promotion
.From<PromotionAppliedWithNestedPromotion>()
.ClearWith<PromotionRemovedWithNestedPromotion>());
}

View C# snippet source on GitHub

Use Children to manage several independently identified items within a parent. For control over which nested properties map by name, continue with AutoMap. If you have not defined a projection yet, start with a simple projection.