Skip to content

Cratis Chronicle model-bound projections: Map properties

Use model-bound mapping in Cratis Chronicle when a read model property needs a value from an event or its metadata. Declare the mapping on the read model: you can replace a value, add or subtract an amount, or record when a particular event occurred.

Client syntax differs. The examples below show each client’s way to declare the event type, the key that selects a read model instance, and the property mappings.

A set mapping replaces the current read model value with a property from the event. Use an explicit source name when the event and read model name the value differently.

Model-bound set mapping
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Keys;
using Cratis.Chronicle.Projections.ModelBound;
[EventType]
public record UserRegisteredForContact(string Name, string Email);
public record UserContact(
[Key] Guid Id,
[SetFrom<UserRegisteredForContact>(nameof(UserRegisteredForContact.Email))]
string Email,
[SetFrom<UserRegisteredForContact>(nameof(UserRegisteredForContact.Name))]
string Name);

View C# snippet source on GitHub

When the names match, you can omit the source property name. For a whole event whose properties match the read model, consider convention-based mapping.

Convention-based set mapping
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Keys;
using Cratis.Chronicle.Projections.ModelBound;
[EventType]
public record UserRegisteredForProfile(string Name, string Email);
[FromEvent<UserRegisteredForProfile>]
public record UserProfile(
[Key] Guid Id,
string Name,
string Email);

View C# snippet source on GitHub

Put multiple set mappings on a property when different event types supply its value. Each mapping replaces the current value when its event is processed.

Multiple set mappings
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Keys;
using Cratis.Chronicle.Projections.ModelBound;
[EventType]
public record AccountOpenedForRename(string AccountName);
[EventType]
public record AccountRenamedForRename(string NewName);
public record RenameableAccount(
[Key] Guid Id,
[SetFrom<AccountOpenedForRename>(nameof(AccountOpenedForRename.AccountName))]
[SetFrom<AccountRenamedForRename>(nameof(AccountRenamedForRename.NewName))]
string Name);

View C# snippet source on GitHub

Use an add mapping when an event carries an amount to add, rather than a replacement value. A deposit, for example, increases the balance by the amount in the event.

Add from an event
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Keys;
using Cratis.Chronicle.Projections.ModelBound;
[EventType]
public record AccountOpenedForDeposits(decimal InitialBalance);
[EventType]
public record DepositMadeForBalance(decimal Amount);
public record DepositAccount(
[Key] Guid Id,
[SetFrom<AccountOpenedForDeposits>(nameof(AccountOpenedForDeposits.InitialBalance))]
[AddFrom<DepositMadeForBalance>(nameof(DepositMadeForBalance.Amount))]
decimal Balance);

View C# snippet source on GitHub

A subtract mapping deducts the event’s amount from the current value. Combine the two operations to track a net balance:

Subtract from an event
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Keys;
using Cratis.Chronicle.Projections.ModelBound;
[EventType]
public record BalanceAccountOpened(decimal InitialBalance);
[EventType]
public record BalanceDepositMade(decimal Amount);
[EventType]
public record BalanceWithdrawalMade(decimal Amount);
public record BalanceAccount(
[Key] Guid Id,
[SetFrom<BalanceAccountOpened>(nameof(BalanceAccountOpened.InitialBalance))]
[AddFrom<BalanceDepositMade>(nameof(BalanceDepositMade.Amount))]
[SubtractFrom<BalanceWithdrawalMade>(nameof(BalanceWithdrawalMade.Amount))]
decimal Balance);

View C# snippet source on GitHub

In this account read model, opening the account sets its name and initial balance. Deposits and withdrawals adjust the balance; renaming replaces the name without changing the balance.

Complete balance projection
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Keys;
using Cratis.Chronicle.Projections.ModelBound;
[EventType]
public record BankAccountOpened(string AccountName, decimal InitialBalance);
[EventType]
public record BankAccountRenamed(string NewName);
[EventType]
public record FundsDeposited(decimal Amount);
[EventType]
public record FundsWithdrawn(decimal Amount);
public record BankAccount(
[Key] Guid Id,
[SetFrom<BankAccountOpened>(nameof(BankAccountOpened.AccountName))]
[SetFrom<BankAccountRenamed>(nameof(BankAccountRenamed.NewName))]
string Name,
[SetFrom<BankAccountOpened>(nameof(BankAccountOpened.InitialBalance))]
[AddFrom<FundsDeposited>(nameof(FundsDeposited.Amount))]
[SubtractFrom<FundsWithdrawn>(nameof(FundsWithdrawn.Amount))]
decimal Balance);

View C# snippet source on GitHub

Event context is metadata stored alongside the event payload. It includes occurrence time, event source identity, sequence information, and correlation metadata. Use a context mapping when the read model needs one of these values rather than a field from the payload.

Map event context
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Keys;
using Cratis.Chronicle.Projections.ModelBound;
[EventType]
public record OrderPlacedForAudit(string CustomerName);
public record AuditedOrder(
[Key] Guid Id,
[SetFrom<OrderPlacedForAudit>(nameof(OrderPlacedForAudit.CustomerName))]
string CustomerName,
[SetFromContext<OrderPlacedForAudit>(nameof(EventContext.Occurred))]
DateTimeOffset OrderedAt);

View C# snippet source on GitHub

Choose FromEvery when a property should update for every event the projection subscribes to. In the next example, placement and shipment timestamps belong to specific events, while LastModified records the latest subscribed event.

Specific context vs every event
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Keys;
using Cratis.Chronicle.Projections.ModelBound;
[EventType]
public record OrderPlacedForLifecycle(string CustomerName);
[EventType]
public record OrderShippedForLifecycle(string TrackingNumber);
public record OrderLifecycle(
[Key] Guid Id,
[SetFromContext<OrderPlacedForLifecycle>(nameof(EventContext.Occurred))]
DateTimeOffset PlacedAt,
[SetFromContext<OrderShippedForLifecycle>(nameof(EventContext.Occurred))]
DateTimeOffset? ShippedAt,
[FromEvery(contextProperty: nameof(EventContext.Occurred))]
DateTimeOffset LastModified);

View C# snippet source on GitHub

In .NET, use [SetFromEventSourceId<TEvent>] to copy the event’s source identifier to a read model property. It emits $eventSourceId, just like the fluent .Set(...).ToEventSourceId() mapping, without a string expression.

Map the event source identifier
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Keys;
using Cratis.Chronicle.Projections.ModelBound;
[EventType]
public record OrderPlacedWithSourceId(string CustomerName);
public record OrderEventSourceReference(
[Key] Guid Id,
[SetFromEventSourceId<OrderPlacedWithSourceId>] EventSourceId Source);

View C# snippet source on GitHub

The attribute works on properties and record parameters, including child records. Each mapping applies only to its declared event type. Use SetOnce = true to keep the first identifier. For other context metadata, keep using SetFromContext; existing SetFromContext<TEvent>(nameof(EventContext.EventSourceId)) mappings continue to emit $eventContext(EventSourceId).

To group events by week, derive the week number from their occurrence time. Occurred.Week and Occurred.Week() both select the ISO week number. Pair it with Occurred.WeekYear, the ISO week-numbering year, which can differ from the calendar year near New Year.

These paths work on properties and record parameters with [SetFromContext<T>], and with [FromEvery(contextProperty: ...)].

Map derived event context
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Keys;
using Cratis.Chronicle.Projections.ModelBound;
[EventType]
public record AccountOpenedForWeeklyAudit(string Name);
public record WeeklyAccountAudit(
[Key] Guid Id,
[SetFromContext<AccountOpenedForWeeklyAudit>("Occurred.Week")]
int OpenedWeek,
[SetFromContext<AccountOpenedForWeeklyAudit>("Occurred.WeekYear")]
int OpenedWeekYear,
[FromEvery(contextProperty: "Occurred.Week()")]
int LastUpdatedWeek);

View C# snippet source on GitHub

In .NET, the function must be the final path segment, take no arguments, and support the type of the value it reads. Week and WeekYear support DateTimeOffset, DateTime, and DateOnly, including nullable values. Unknown functions and incompatible value types are rejected when building the projection.

An actual .NET property takes precedence over a bare function name. Naming policies apply to property segments, not function names: under camel casing, Occurred.Week becomes $eventContext(occurred.Week()).

Set SetOnce = true on SetFrom or SetFromContext when a property should keep the first value it gets. The mapping assigns the value only while the property has no value - it is missing or null - and later events leave it unchanged. In the next example every revision updates Title, while OriginalTitle and Created keep what the first revision supplied:

Set a value only once
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Keys;
using Cratis.Chronicle.Projections.ModelBound;
[EventType]
public record DocumentRevisedForSetOnce(string Title);
public record SetOnceDocument(
[Key] Guid Id,
[SetFrom<DocumentRevisedForSetOnce>(nameof(DocumentRevisedForSetOnce.Title), SetOnce = true)]
string OriginalTitle,
[SetFrom<DocumentRevisedForSetOnce>]
string Title,
[SetFromContext<DocumentRevisedForSetOnce>(nameof(EventContext.Occurred), SetOnce = true)]
DateTimeOffset Created);

View C# snippet source on GitHub

Set once works on root properties, children and nested objects, and a replay assigns the same value. See setting a value only once for the full behavior.

Mapping Use it when
Set A read model property should take a value from a specific event.
Set once A property should keep the first value an event supplies, such as who created something or when.
Add A numeric property should increase when an event occurs.
Subtract A numeric property should decrease when an event occurs.
Context A read model property should come from event metadata.
Every event A property should update for any event that affects the projection.

For changes of exactly one, use counters; for a value that should become null, use clearing. If the mapping needs branching, state-dependent logic, or calculations that are clearer as code, use a reducer instead.