Skip to content

Cratis Chronicle projections: build child collections

Child collections in Cratis Chronicle let you keep related items inside one read model, such as members inside a group. Configure both the parent key, which selects the group, and the child key, which selects the member to add, update, or remove.

Use Children to select the collection property, then IdentifiedBy() to select the property that identifies each stored child. Each event mapping supplies the child key with UsingKey(). The example maps group details at the root and membership changes inside Members.

Projection with children
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Projections;
[EventType]
public record GroupCreatedForChildren(string Name, string Description);
[EventType]
public record UserAddedToGroupForChildren(string UserId, string Role);
[EventType]
public record UserRoleChangedForChildren(string UserId, string Role);
[EventType]
public record UserRemovedFromGroupForChildren(string UserId);
public record GroupForChildren(
string Name,
string Description,
IEnumerable<GroupMemberForChildren> Members);
public record GroupMemberForChildren(
string UserId,
string Role);
public class GroupProjectionForChildren : IProjectionFor<GroupForChildren>
{
public void Define(IProjectionBuilderFor<GroupForChildren> builder) => builder
.From<GroupCreatedForChildren>()
.Children(m => m.Members, children => children
.IdentifiedBy(m => m.UserId)
.From<UserAddedToGroupForChildren>(b => b
.UsingKey(e => e.UserId))
.From<UserRoleChangedForChildren>(b => b
.UsingKey(e => e.UserId))
.RemovedWith<UserRemovedFromGroupForChildren>(b => b
.UsingKey(e => e.UserId)));
}

View C# snippet source on GitHub

The read model includes a collection property for the children:

Read model with children
public record GroupWithMembers(
string Name,
string Description,
IEnumerable<GroupMember> Members);
public record GroupMember(
string UserId,
string Role);

View C# snippet source on GitHub

Membership events carry a UserId so the projection can find the affected member. The event source ID will identify the parent group in this example:

Child lifecycle events
using Cratis.Chronicle.Events;
[EventType]
public record GroupCreatedForChildEvents(string Name, string Description);
[EventType]
public record UserAddedToGroupForChildEvents(string UserId, string Role);
[EventType]
public record UserRoleChangedForChildEvents(string UserId, string Role);
[EventType]
public record UserRemovedFromGroupForChildEvents(string UserId);

View C# snippet source on GitHub

The root From mapping updates group details. The mappings inside Children update members instead. For each membership event, Chronicle first resolves the parent group, then matches the event’s child key against the property selected by IdentifiedBy().

A member with that key is updated if it exists, or added if it does not. Removal uses a separate RemovedWith<>() mapping.

By default, Chronicle uses EventSourceId, the identifier attached when the event is appended, as the parent key. Leave that default when membership events are appended under the group’s ID. Choose a parent key from event content when they are appended under another ID, such as the user’s.

Default behavior (EventSourceId as parent key)

Section titled “Default behavior (EventSourceId as parent key)”

When the event source ID is the group’s ID, only the child key needs an explicit mapping:

Default parent key
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Projections;
[EventType]
public record GroupCreatedWithDefaultParentKey(string Name);
[EventType]
public record UserAddedWithDefaultParentKey(string UserId, string Role);
public record GroupWithDefaultParentKey(
string Name,
IEnumerable<GroupMemberWithDefaultParentKey> Members);
public record GroupMemberWithDefaultParentKey(
string UserId,
string Role);
public class GroupWithDefaultParentKeyProjection : IProjectionFor<GroupWithDefaultParentKey>
{
public void Define(IProjectionBuilderFor<GroupWithDefaultParentKey> builder) => builder
.From<GroupCreatedWithDefaultParentKey>()
.Children(m => m.Members, children => children
.IdentifiedBy(m => m.UserId)
.From<UserAddedWithDefaultParentKey>(b => b
.UsingKey(e => e.UserId)));
}

View C# snippet source on GitHub

When you append the event:

Append child event to parent
using Cratis.Chronicle;
using Cratis.Chronicle.Events;
using Cratis.Chronicle.EventSequences;
public class GroupMembershipWithDefaultParentKey(IEventStore eventStore)
{
public Task AddUserToGroup(EventSourceId groupId, string userId, string role) =>
eventStore.EventLog.Append(groupId, new UserAddedWithDefaultParentKey(userId, role));
}

View C# snippet source on GitHub

The groupId passed to Append selects the parent group. The event’s UserId selects the member within it.

Use UsingParentKey() when the event contains the parent’s ID but is appended under a different event source ID:

Parent key from event content
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Projections;
[EventType]
public record GroupCreatedWithEventParentKey(string Name);
[EventType]
public record UserAddedWithEventParentKey(string GroupId, string UserId, string Role);
public record GroupWithEventParentKey(
string Name,
IEnumerable<GroupMemberWithEventParentKey> Members);
public record GroupMemberWithEventParentKey(
string UserId,
string Role);
public class GroupWithEventParentKeyProjection : IProjectionFor<GroupWithEventParentKey>
{
public void Define(IProjectionBuilderFor<GroupWithEventParentKey> builder) => builder
.From<GroupCreatedWithEventParentKey>()
.Children(m => m.Members, children => children
.IdentifiedBy(m => m.UserId)
.From<UserAddedWithEventParentKey>(b => b
.UsingParentKey(e => e.GroupId)
.UsingKey(e => e.UserId)));
}

View C# snippet source on GitHub

When you append the event:

Append child event with parent key
using Cratis.Chronicle;
using Cratis.Chronicle.Events;
using Cratis.Chronicle.EventSequences;
public class GroupMembershipWithEventParentKey(IEventStore eventStore)
{
public Task AddUserToGroup(EventSourceId userId, string groupId, string role) =>
eventStore.EventLog.Append(userId, new UserAddedWithEventParentKey(groupId, userId.Value, role));
}

View C# snippet source on GitHub

Here, the event is appended under userId. Its GroupId property selects the parent group, and UserId still selects the member.

Using EventSourceId explicitly with UsingParentKeyFromContext

Section titled “Using EventSourceId explicitly with UsingParentKeyFromContext”

Use UsingParentKeyFromContext(ctx => ctx.EventSourceId) if you want the default parent-key choice to be visible in the definition:

Explicit parent key from context
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Projections;
[EventType]
public record GroupCreatedWithContextParentKey(string Name);
[EventType]
public record UserAddedWithContextParentKey(string UserId, string Role);
public record GroupWithContextParentKey(
string Name,
IEnumerable<GroupMemberWithContextParentKey> Members);
public record GroupMemberWithContextParentKey(
string UserId,
string Role);
public class GroupWithContextParentKeyProjection : IProjectionFor<GroupWithContextParentKey>
{
public void Define(IProjectionBuilderFor<GroupWithContextParentKey> builder) => builder
.From<GroupCreatedWithContextParentKey>()
.Children(m => m.Members, children => children
.IdentifiedBy(m => m.UserId)
.From<UserAddedWithContextParentKey>(b => b
.UsingParentKeyFromContext(c => c.EventSourceId)
.UsingKey(e => e.UserId)));
}

View C# snippet source on GitHub

This selects the same parent as leaving the parent key unspecified.

Parent identifier location Mapping
Event source ID Leave the parent key unspecified.
Event content Use UsingParentKey(e => e.Property).
Event source ID, stated explicitly Use UsingParentKeyFromContext(ctx => ctx.EventSourceId).

A From mapping adds a child when its key is new and updates the child when the key already exists. This means an event named as an update can also create a missing child. Use RemovedWith<>() for removal rather than mapping a deletion event through From.

In the .NET client, use AddChild(collection, eventProperty) inside a From mapping to append an event property directly to a collection of primitive values, such as strings. Each event adds one value, including repeated values. Unlike object children, these values do not need an IdentifiedBy property or a child key; the event source ID selects the parent read model.

The resulting child definition uses FromEventProperty. For older definitions that also contain an ordinary child From for the same event, Chronicle uses the event property only, so the value is added once.

Configure the removal event with the same child-key strategy used by the add and update mappings:

Remove children
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Projections;
[EventType]
public record GroupCreatedWithRemoval(string Name);
[EventType]
public record UserAddedWithRemoval(string UserId, string Role);
[EventType]
public record UserRemovedWithRemoval(string UserId);
public record GroupWithRemoval(
string Name,
IEnumerable<GroupMemberWithRemoval> Members);
public record GroupMemberWithRemoval(
string UserId,
string Role);
public class GroupWithRemovalProjection : IProjectionFor<GroupWithRemoval>
{
public void Define(IProjectionBuilderFor<GroupWithRemoval> builder) => builder
.From<GroupCreatedWithRemoval>()
.Children(m => m.Members, children => children
.IdentifiedBy(m => m.UserId)
.From<UserAddedWithRemoval>(b => b
.UsingKey(e => e.UserId))
.RemovedWith<UserRemovedWithRemoval>(b => b
.UsingKey(e => e.UserId)));
}

View C# snippet source on GitHub

When the removal event arrives, Chronicle finds the member by e.UserId and removes it. If no member has that key, the collection stays unchanged. Add separate RemovedWith<>() mappings for other event types that remove members.

By default a new child is appended to the end of the collection. A children definition can instead choose where new children go:

Placement Where a new child goes
Append (default) At the end of the collection.
Prepend At the start of the collection, so the most recent child comes first.
Sorted The collection is ordered by a child property after the new child is inserted, ascending or descending.

The order is stored, not computed when the read model is queried. Chronicle applies it at the moment a child is added, in the projection engine and in every sink, so a replay produces the same order.

Ordering only places new children. Updating an existing child never moves it, even when the update changes the property the collection is sorted by. Removing a child leaves the others where they are.

Children with equal sort values are ordered by the property that identifies them, ascending, in both directions, so the order is the same in every sink. Children with a missing or null sort value come first when sorting ascending and last when sorting descending.

Values compare the same way regardless of the server’s culture: numbers numerically across numeric types, strings by their character codes (so B comes before a), dates as UTC instants to the millisecond, false before true, and GUIDs by their stored bytes. When a collection mixes kinds of values, null comes first, then numbers, strings, GUIDs, booleans and dates. Because the whole collection is ordered on each insert, a child whose sort value changed since it was added takes its sorted place the next time a child is inserted.

In the next example the newest comment comes first, and tasks stay sorted with the highest priority first:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Projections;
[EventType]
public record DecOrderingCommentPosted(Guid CommentId, string Text);
[EventType]
public record DecOrderingTaskAdded(Guid TaskId, string Title, int Priority);
public record DecOrderingComment(Guid CommentId, string Text);
public record DecOrderingTask(Guid TaskId, string Title, int Priority);
public record DecOrderingBoard(IEnumerable<DecOrderingComment> Comments, IEnumerable<DecOrderingTask> Tasks);
public class DecOrderingBoardProjection : IProjectionFor<DecOrderingBoard>
{
public void Define(IProjectionBuilderFor<DecOrderingBoard> builder) => builder
.Children(m => m.Comments, children => children
.IdentifiedBy(c => c.CommentId)
.Prepend()
.From<DecOrderingCommentPosted>(_ => _.UsingKey(e => e.CommentId)))
.Children(m => m.Tasks, children => children
.IdentifiedBy(t => t.TaskId)
.OrderByDescending(t => t.Priority)
.From<DecOrderingTaskAdded>(_ => _.UsingKey(e => e.TaskId)));
}

View C# snippet source on GitHub

A collection has one ordering. Declaring a second one for the same collection fails when the projection is built.

Call Children for each collection the read model needs. Each collection has its own identity and event mappings:

Multiple child collections
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Projections;
[EventType]
public record GroupCreatedWithMultipleCollections(string Name);
[EventType]
public record MemberAddedToGroup(string UserId, string Role);
[EventType]
public record TaskAssignedToGroup(string TaskId, string Title);
public record GroupWithMultipleCollections(
string Name,
IEnumerable<GroupMemberInMultipleCollections> Members,
IEnumerable<GroupTaskInMultipleCollections> Tasks);
public record GroupMemberInMultipleCollections(
string UserId,
string Role);
public record GroupTaskInMultipleCollections(
string TaskId,
string Title);
public class GroupWithMultipleCollectionsProjection : IProjectionFor<GroupWithMultipleCollections>
{
public void Define(IProjectionBuilderFor<GroupWithMultipleCollections> builder) => builder
.From<GroupCreatedWithMultipleCollections>()
.Children(m => m.Members, children => children
.IdentifiedBy(m => m.UserId)
.From<MemberAddedToGroup>(b => b
.UsingKey(e => e.UserId)))
.Children(m => m.Tasks, children => children
.IdentifiedBy(m => m.TaskId)
.From<TaskAssignedToGroup>(b => b
.UsingKey(e => e.TaskId)));
}

View C# snippet source on GitHub

If a child needs several values to identify it, continue with composite keys. For an object without a collection, use a nested projection.