Skip to content

Chronicle declarative projections with fluent mappings

Cratis Chronicle declarative projections turn events into read models through a fluent definition kept separate from the model type. Use them when you need to control property mappings, choose keys, or combine related data without putting projection attributes on the read model.

In .NET, implement IProjectionFor<TReadModel> and use the IProjectionBuilderFor<TReadModel> passed to Define to declare the events and mappings. Chronicle executes the resulting definition as events are processed and stores the derived state for queries. You describe how a view changes rather than writing code to save it after each event.

Start by declaring the event types that contribute to the read model. The client tabs show the corresponding definition syntax:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Projections;
[EventType]
public record DecIndexUserRegistered(string Name, string Email, DateTimeOffset RegisteredAt);
public record DecIndexUserProfile(string Name, string Email, DateTimeOffset RegisteredAt);
public class DecIndexUserProfileProjection : IProjectionFor<DecIndexUserProfile>
{
public void Define(IProjectionBuilderFor<DecIndexUserProfile> builder) => builder
.From<DecIndexUserRegistered>();
}

View C# snippet source on GitHub

Auto-mapping copies event properties to read model properties with matching names. It is enabled by default unless the model or scope disables it. Use .Set() when names differ, or .Add() and .Subtract() when an event contributes a change to a running total rather than a replacement value.

In .NET, implementing IProjectionFor<TReadModel> makes a projection type discoverable. Register its events in the event-type registry, normally through [EventType] or explicit event nominations. Other clients use their own registration conventions, as shown in the examples.

In .NET, a projection class must target only one read model. Implementing two closed IProjectionFor<TReadModel> interfaces, including through inheritance, throws TypeImplementsMultipleProjectionInterfaces during default artifact discovery. Split the class into one projection per read model. CHR0057 reports this before runtime.

Choose the relationship according to the view you need to read. Children manages several identified items within one parent; Nested manages one optional object. Joins brings facts from independent event streams into the same read model.

For fields shared across event types, FromEvery applies mappings to events the projection already handles. It does not subscribe to all event types; FromAll does. Both can use event metadata, such as occurrence times, without repeating the same mapping in each event declaration.

For a view that mainly copies named event properties, start with model-bound attributes. Choose a fluent definition when relationships, keys, or an attribute-free model make the mapping easier to follow. If the logic is clearer as state-transition code, consider a self-reducing model instead. Choose how to build a read model compares those options and their limits.

Define builds a kernel-executed definition, not a per-event handler. Dependencies can help construct that definition, but the builder lambdas do not run arbitrary injected logic for each event.

Recipe Description
Simple projection Declare events and use the default AutoMap behavior
AutoMap Automatic property mapping at different levels
Passive In-memory projections for on-demand lookups
Set properties Explicit property mapping and transformations
Children Hierarchical data models with child collections
Nested Populate and clear one optional object within a parent
Joins Cross-stream projections using joins
Functions Maintain counters and running totals
Composite keys Multi-property key identification
Event context Using event metadata in projections
FromEvery Setting properties for all events in a projection
FromAll Subscribe to all event types without filtering
Initial values Default values for read model properties
RemoveWithJoin Cross-stream child removal
FromEventSequence Sourcing events from specific event sequences
NotRewindable Set IsRewindable to false on the projection definition
Variants Mutually exclusive read model shapes for the same logical entity

Once events have populated the projection, use the .NET IReadModels API to read the stored view. Choose the operation your application needs:

Use auto-mapping when an event property and its read model target have the same name. Fluent projections enable it by default; call .AutoMap() to re-enable it in a scope that disabled it. In model-bound projections, [FromEvent<TEvent>] supplies name-based mapping.

Use explicit mappings when a name differs or the operation is not assignment. In fluent projections, .Set() copies a value and .Add() accumulates one. Model-bound projections express those operations with attributes such as [SetFrom<TEvent>] and [AddFrom<TEvent>]. See AutoMap for inheritance and overrides.

A projection can handle multiple event types, each with its own mappings. Events update the properties they map; they do not replace the entire read model. Use Initial values for properties that need a meaningful starting value before an event assigns them.

The event source ID is the default key for the read model and the default parent key for child events. When an event carries a different parent identifier in its payload, use .UsingParentKey(e => e.Property). .UsingParentKeyFromContext(ctx => ctx.EventSourceId) makes the default parent choice explicit.

A child collection also needs an item identity. Declare the target with .IdentifiedBy(), and use .UsingKey(e => e.Property) when the child’s identifier comes from event content. The Children recipe shows how parent and child keys work together.

A root join selects a relationship through .On(m => m.Property). That property identifies the related stream, not the read model’s own key. Follow Joins before combining sources that have different event source IDs.

By default the read model is stored in a container (collection, table) named by the client’s naming policy. In C#, call ContainerName("name") on the projection builder to choose a different one. This sets only the container name; the read model keeps its identifier, so the projection still resolves its read model. Every projection of the same read model must use the same container name, otherwise the client reports a conflict. Changing the container name of a read model that already has data points it at a new, empty container, so replay the projection afterwards.

Shape the read model around the query it should answer. A joined event can affect many instances, so consider how many read models share its key and how often that data changes. For a first implementation, start with the simple projection recipe, then add only the relationships and calculations the view needs.