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.
Overview
Section titled “Overview”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.
Basic Example
Section titled “Basic Example”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>();}import io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.projections.IProjectionBuilderForimport io.cratis.chronicle.projections.IProjectionForimport java.time.OffsetDateTime
@EventTypedata class DecIndexUserRegistered(val name: String, val email: String, val registeredAt: OffsetDateTime)
data class DecIndexUserProfile( val name: String = "", val email: String = "", val registeredAt: OffsetDateTime? = null)
class DecIndexUserProfileProjection : IProjectionFor<DecIndexUserProfile> { override fun define(builder: IProjectionBuilderFor<DecIndexUserProfile>) { builder.from(DecIndexUserRegistered::class) }}import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.projections.IProjectionBuilderFor;import io.cratis.chronicle.projections.IProjectionFor;
@EventTyperecord DecIndexUserRegistered(String name, String email, String registeredAt) {}
class DecIndexUserProfile { public String name = ""; public String email = ""; public String registeredAt = null;}
class DecIndexUserProfileProjection implements IProjectionFor<DecIndexUserProfile> { @Override public void define(IProjectionBuilderFor<DecIndexUserProfile> builder) { builder.from(DecIndexUserRegistered.class); }}defmodule MyApp.Events.DecIndexUserRegistered do use Cratis.Chronicle.Events.EventType, id: "dec-index-user-registered"
defstruct [:name, :email, :registered_at]end
defmodule MyApp.ReadModels.DecIndexUserProfile do use Cratis.Chronicle.ReadModels.ReadModel
defstruct [:name, :email, :registered_at]end
defmodule MyApp.Projections.DecIndexUserProfileProjection do use Cratis.Chronicle.Projections.Projection, model: MyApp.ReadModels.DecIndexUserProfile
alias MyApp.Events.DecIndexUserRegistered
from DecIndexUserRegisteredendimport { eventType, IProjectionBuilderFor, IProjectionFor, projection } from '@cratis/chronicle';
@eventType()class DecIndexUserRegistered { name = ''; email = ''; registeredAt = new Date();}
class DecIndexUserProfile { name = ''; email = ''; registeredAt = new Date();}
@projection()class DecIndexUserProfileProjection implements IProjectionFor<DecIndexUserProfile> { define(builder: IProjectionBuilderFor<DecIndexUserProfile>): void { builder.from(DecIndexUserRegistered); }}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.
Discovery
Section titled “Discovery”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.
Key Features
Section titled “Key Features”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.
When to Use
Section titled “When to Use”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.
Projection recipes
Section titled “Projection recipes”| 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 |
Reading Your Declarative Projections
Section titled “Reading Your Declarative Projections”Once events have populated the projection, use the .NET IReadModels API to read the stored view. Choose the operation your application needs:
- Getting a Single Instance - Retrieve a specific instance by key
- Getting a Collection of Instances - Retrieve all instances for reporting and analysis
- Getting Snapshots - Retrieve historical state snapshots grouped by correlation ID
- Watching Read Models - Observe real-time changes as events are applied
Key concepts
Section titled “Key concepts”Auto-mapping vs explicit mapping
Section titled “Auto-mapping vs explicit mapping”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.
Event handling
Section titled “Event handling”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.
Keys and identification
Section titled “Keys and identification”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.
Container name
Section titled “Container name”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.
Performance
Section titled “Performance”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.