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.
Set A Property From An Event
Section titled “Set A Property From An Event”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.
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);import io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.projections.FromEventimport io.cratis.chronicle.projections.SetFromimport io.cratis.chronicle.readModels.ReadModel
@EventTypedata class UserRegisteredForContact( val name: String, val email: String)
@ReadModel@FromEvent(UserRegisteredForContact::class)data class UserContact( @SetFrom("email", UserRegisteredForContact::class) val email: String = "",
@SetFrom("name", UserRegisteredForContact::class) val name: String = "")import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.projections.FromEvent;import io.cratis.chronicle.projections.SetFrom;import io.cratis.chronicle.readModels.ReadModel;
@EventTyperecord UserRegisteredForContact(String name, String email) {}
@ReadModel@FromEvent(eventType = UserRegisteredForContact.class)class UserContact { @SetFrom(propertyPath = "email", eventType = UserRegisteredForContact.class) public String email = "";
@SetFrom(propertyPath = "name", eventType = UserRegisteredForContact.class) public String name = "";}defmodule MyApp.Events.UserRegisteredForContact do use Cratis.Chronicle.Events.EventType, id: "user-registered-for-contact-v1"
defstruct [:name, :email]end
defmodule MyApp.ReadModels.UserContact do use Cratis.Chronicle.ReadModels.ReadModel
alias MyApp.Events.UserRegisteredForContact
defstruct [:id, :name, :email]
from UserRegisteredForContact, set: [ id: :event_source_id, email: :email, name: :name ]endimport { eventType, fromEvent, setFrom } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()export class UserRegisteredForContact { @field(String) readonly name: string; @field(String) readonly email: string;
constructor(name: string, email: string) { this.name = name; this.email = email; }}
@fromEvent(UserRegisteredForContact)export class UserContact { @setFrom(UserRegisteredForContact, 'email') email = '';
@setFrom(UserRegisteredForContact, 'name') name = '';}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.
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);import io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.projections.FromEventimport io.cratis.chronicle.projections.SetFromimport io.cratis.chronicle.readModels.ReadModel
@EventTypedata class UserRegisteredForProfile( val name: String, val email: String)
@ReadModel@FromEvent(UserRegisteredForProfile::class)data class UserProfile( @SetFrom val name: String = "",
@SetFrom val email: String = "")import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.projections.FromEvent;import io.cratis.chronicle.projections.SetFrom;import io.cratis.chronicle.readModels.ReadModel;
@EventTyperecord UserRegisteredForProfile(String name, String email) {}
@ReadModel@FromEvent(eventType = UserRegisteredForProfile.class)class UserProfile { @SetFrom public String name = "";
@SetFrom public String email = "";}defmodule MyApp.Events.UserRegisteredForProfile do use Cratis.Chronicle.Events.EventType, id: "user-registered-for-profile"
defstruct [:name, :email]end
defmodule MyApp.ReadModels.UserProfile do use Cratis.Chronicle.ReadModels.ReadModel
alias MyApp.Events.UserRegisteredForProfile
defstruct [:id, :name, :email]
# `name` and `email` are mapped automatically from the matching event # fields by convention — only the key/id needs to be told where to come # from. from UserRegisteredForProfile, set: [id: :event_source_id]endimport { eventType, fromEvent, setFrom } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()export class UserRegisteredForProfile { @field(String) readonly name: string; @field(String) readonly email: string;
constructor(name: string, email: string) { this.name = name; this.email = email; }}
@fromEvent(UserRegisteredForProfile)export class UserProfile { @setFrom(UserRegisteredForProfile) name = '';
@setFrom(UserRegisteredForProfile) email = '';}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.
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);import io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.projections.FromEventimport io.cratis.chronicle.projections.SetFromimport io.cratis.chronicle.readModels.ReadModel
@EventTypedata class AccountOpenedForRename( val accountName: String)
@EventTypedata class AccountRenamedForRename( val newName: String)
@ReadModel@FromEvent(AccountOpenedForRename::class)@FromEvent(AccountRenamedForRename::class)data class RenameableAccount( @SetFrom("accountName", AccountOpenedForRename::class) @SetFrom("newName", AccountRenamedForRename::class) val name: String = "")import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.projections.FromEvent;import io.cratis.chronicle.projections.SetFrom;import io.cratis.chronicle.readModels.ReadModel;
@EventTyperecord AccountOpenedForRename(String accountName) {}
@EventTyperecord AccountRenamedForRename(String newName) {}
@ReadModel@FromEvent(eventType = AccountOpenedForRename.class)@FromEvent(eventType = AccountRenamedForRename.class)class RenameableAccount { @SetFrom(propertyPath = "accountName", eventType = AccountOpenedForRename.class) @SetFrom(propertyPath = "newName", eventType = AccountRenamedForRename.class) public String name = "";}defmodule MyApp.Events.AccountOpenedForRename do use Cratis.Chronicle.Events.EventType, id: "account-opened-for-rename-v1"
defstruct [:account_name]end
defmodule MyApp.Events.AccountRenamedForRename do use Cratis.Chronicle.Events.EventType, id: "account-renamed-for-rename-v1"
defstruct [:new_name]end
defmodule MyApp.ReadModels.RenameableAccount do use Cratis.Chronicle.ReadModels.ReadModel
alias MyApp.Events.{AccountOpenedForRename, AccountRenamedForRename}
defstruct [:id, :name]
from AccountOpenedForRename, set: [ id: :event_source_id, name: :account_name ]
from AccountRenamedForRename, set: [name: :new_name]endimport { eventType, fromEvent, setFrom } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()export class AccountOpenedForRename { @field(String) readonly accountName: string;
constructor(accountName: string) { this.accountName = accountName; }}
@eventType()export class AccountRenamedForRename { @field(String) readonly newName: string;
constructor(newName: string) { this.newName = newName; }}
@fromEvent(AccountOpenedForRename)@fromEvent(AccountRenamedForRename)export class RenameableAccount { @setFrom(AccountOpenedForRename, 'accountName') @setFrom(AccountRenamedForRename, 'newName') name = '';}Add And Subtract Values
Section titled “Add And Subtract Values”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.
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);import io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.projections.AddFromimport io.cratis.chronicle.projections.FromEventimport io.cratis.chronicle.projections.SetFromimport io.cratis.chronicle.readModels.ReadModel
@EventTypedata class AccountOpenedForDeposits(val initialBalance: Double)
@EventTypedata class DepositMadeForBalance(val amount: Double)
@ReadModel@FromEvent(AccountOpenedForDeposits::class)@FromEvent(DepositMadeForBalance::class)data class DepositAccount( @SetFrom("initialBalance", AccountOpenedForDeposits::class) @AddFrom(DepositMadeForBalance::class, "amount") val balance: Double = 0.0)import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.projections.AddFrom;import io.cratis.chronicle.projections.FromEvent;import io.cratis.chronicle.projections.SetFrom;import io.cratis.chronicle.readModels.ReadModel;
@EventTyperecord AccountOpenedForDeposits(double initialBalance) {}
@EventTyperecord DepositMadeForBalance(double amount) {}
@ReadModel@FromEvent(eventType = AccountOpenedForDeposits.class)@FromEvent(eventType = DepositMadeForBalance.class)class DepositAccount { @SetFrom(propertyPath = "initialBalance", eventType = AccountOpenedForDeposits.class) @AddFrom(eventType = DepositMadeForBalance.class, eventPropertyName = "amount") public double balance = 0.0;}defmodule MyApp.Events.AccountOpenedForDeposits do use Cratis.Chronicle.Events.EventType, id: "account-opened-for-deposits-v1"
defstruct [:initial_balance]end
defmodule MyApp.Events.DepositMadeForBalance do use Cratis.Chronicle.Events.EventType, id: "deposit-made-for-balance-v1"
defstruct [:amount]end
defmodule MyApp.ReadModels.DepositAccount do use Cratis.Chronicle.ReadModels.ReadModel
alias MyApp.Events.{AccountOpenedForDeposits, DepositMadeForBalance}
defstruct [:id, balance: 0]
from AccountOpenedForDeposits, set: [ id: :event_source_id, balance: :initial_balance ]
from DepositMadeForBalance, add: [balance: :amount]endimport { addFrom, eventType, fromEvent, setFrom } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()export class AccountOpenedForDeposits { @field(Number) readonly initialBalance: number;
constructor(initialBalance: number) { this.initialBalance = initialBalance; }}
@eventType()export class DepositMadeForBalance { @field(Number) readonly amount: number;
constructor(amount: number) { this.amount = amount; }}
@fromEvent(AccountOpenedForDeposits)@fromEvent(DepositMadeForBalance)export class DepositAccount { @setFrom(AccountOpenedForDeposits, 'initialBalance') @addFrom(DepositMadeForBalance, 'amount') balance = 0;}A subtract mapping deducts the event’s amount from the current value. Combine the two operations to track a net balance:
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);import io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.projections.AddFromimport io.cratis.chronicle.projections.FromEventimport io.cratis.chronicle.projections.SetFromimport io.cratis.chronicle.projections.SubtractFromimport io.cratis.chronicle.readModels.ReadModel
@EventTypedata class BalanceAccountOpened(val initialBalance: Double)
@EventTypedata class BalanceDepositMade(val amount: Double)
@EventTypedata class BalanceWithdrawalMade(val amount: Double)
@ReadModel@FromEvent(BalanceAccountOpened::class)@FromEvent(BalanceDepositMade::class)@FromEvent(BalanceWithdrawalMade::class)data class BalanceAccount( @SetFrom("initialBalance", BalanceAccountOpened::class) @AddFrom(BalanceDepositMade::class, "amount") @SubtractFrom(BalanceWithdrawalMade::class, "amount") val balance: Double = 0.0)import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.projections.AddFrom;import io.cratis.chronicle.projections.FromEvent;import io.cratis.chronicle.projections.SetFrom;import io.cratis.chronicle.projections.SubtractFrom;import io.cratis.chronicle.readModels.ReadModel;
@EventTyperecord BalanceAccountOpened(double initialBalance) {}
@EventTyperecord BalanceDepositMade(double amount) {}
@EventTyperecord BalanceWithdrawalMade(double amount) {}
@ReadModel@FromEvent(eventType = BalanceAccountOpened.class)@FromEvent(eventType = BalanceDepositMade.class)@FromEvent(eventType = BalanceWithdrawalMade.class)class BalanceAccount { @SetFrom(propertyPath = "initialBalance", eventType = BalanceAccountOpened.class) @AddFrom(eventType = BalanceDepositMade.class, eventPropertyName = "amount") @SubtractFrom(eventType = BalanceWithdrawalMade.class, eventPropertyName = "amount") public double balance = 0.0;}defmodule MyApp.Events.BalanceAccountOpened do use Cratis.Chronicle.Events.EventType, id: "balance-account-opened-v1"
defstruct [:initial_balance]end
defmodule MyApp.Events.BalanceDepositMade do use Cratis.Chronicle.Events.EventType, id: "balance-deposit-made-v1"
defstruct [:amount]end
defmodule MyApp.Events.BalanceWithdrawalMade do use Cratis.Chronicle.Events.EventType, id: "balance-withdrawal-made-v1"
defstruct [:amount]end
defmodule MyApp.ReadModels.BalanceAccount do use Cratis.Chronicle.ReadModels.ReadModel
alias MyApp.Events.{BalanceAccountOpened, BalanceDepositMade, BalanceWithdrawalMade}
defstruct [:id, balance: 0]
from BalanceAccountOpened, set: [ id: :event_source_id, balance: :initial_balance ]
from BalanceDepositMade, add: [balance: :amount]
from BalanceWithdrawalMade, subtract: [balance: :amount]endimport { addFrom, eventType, fromEvent, setFrom, subtractFrom } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()export class BalanceAccountOpened { @field(Number) readonly initialBalance: number;
constructor(initialBalance: number) { this.initialBalance = initialBalance; }}
@eventType()export class BalanceDepositMade { @field(Number) readonly amount: number;
constructor(amount: number) { this.amount = amount; }}
@eventType()export class BalanceWithdrawalMade { @field(Number) readonly amount: number;
constructor(amount: number) { this.amount = amount; }}
@fromEvent(BalanceAccountOpened)@fromEvent(BalanceDepositMade)@fromEvent(BalanceWithdrawalMade)export class BalanceAccount { @setFrom(BalanceAccountOpened, 'initialBalance') @addFrom(BalanceDepositMade, 'amount') @subtractFrom(BalanceWithdrawalMade, 'amount') balance = 0;}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.
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);import io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.projections.AddFromimport io.cratis.chronicle.projections.FromEventimport io.cratis.chronicle.projections.SetFromimport io.cratis.chronicle.projections.SubtractFromimport io.cratis.chronicle.readModels.ReadModel
@EventTypedata class BankAccountOpened(val accountName: String, val initialBalance: Double)
@EventTypedata class BankAccountRenamed(val newName: String)
@EventTypedata class FundsDeposited(val amount: Double)
@EventTypedata class FundsWithdrawn(val amount: Double)
@ReadModel@FromEvent(BankAccountOpened::class)@FromEvent(BankAccountRenamed::class)@FromEvent(FundsDeposited::class)@FromEvent(FundsWithdrawn::class)data class BankAccount( @SetFrom("accountName", BankAccountOpened::class) @SetFrom("newName", BankAccountRenamed::class) val name: String = "",
@SetFrom("initialBalance", BankAccountOpened::class) @AddFrom(FundsDeposited::class, "amount") @SubtractFrom(FundsWithdrawn::class, "amount") val balance: Double = 0.0)import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.projections.AddFrom;import io.cratis.chronicle.projections.FromEvent;import io.cratis.chronicle.projections.SetFrom;import io.cratis.chronicle.projections.SubtractFrom;import io.cratis.chronicle.readModels.ReadModel;
@EventTyperecord BankAccountOpened(String accountName, double initialBalance) {}
@EventTyperecord BankAccountRenamed(String newName) {}
@EventTyperecord FundsDeposited(double amount) {}
@EventTyperecord FundsWithdrawn(double amount) {}
@ReadModel@FromEvent(eventType = BankAccountOpened.class)@FromEvent(eventType = BankAccountRenamed.class)@FromEvent(eventType = FundsDeposited.class)@FromEvent(eventType = FundsWithdrawn.class)class BankAccount { @SetFrom(propertyPath = "accountName", eventType = BankAccountOpened.class) @SetFrom(propertyPath = "newName", eventType = BankAccountRenamed.class) public String name = "";
@SetFrom(propertyPath = "initialBalance", eventType = BankAccountOpened.class) @AddFrom(eventType = FundsDeposited.class, eventPropertyName = "amount") @SubtractFrom(eventType = FundsWithdrawn.class, eventPropertyName = "amount") public double balance = 0.0;}defmodule MyApp.Events.BankAccountOpened do use Cratis.Chronicle.Events.EventType, id: "bank-account-opened-v1"
defstruct [:account_name, :initial_balance]end
defmodule MyApp.Events.BankAccountRenamed do use Cratis.Chronicle.Events.EventType, id: "bank-account-renamed-v1"
defstruct [:new_name]end
defmodule MyApp.Events.FundsDeposited do use Cratis.Chronicle.Events.EventType, id: "funds-deposited-v1"
defstruct [:amount]end
defmodule MyApp.Events.FundsWithdrawn do use Cratis.Chronicle.Events.EventType, id: "funds-withdrawn-v1"
defstruct [:amount]end
defmodule MyApp.ReadModels.BankAccount do use Cratis.Chronicle.ReadModels.ReadModel
alias MyApp.Events.{BankAccountOpened, BankAccountRenamed, FundsDeposited, FundsWithdrawn}
defstruct [:id, :name, balance: 0]
from BankAccountOpened, set: [ id: :event_source_id, name: :account_name, balance: :initial_balance ]
from BankAccountRenamed, set: [name: :new_name]
from FundsDeposited, add: [balance: :amount]
from FundsWithdrawn, subtract: [balance: :amount]endimport { addFrom, eventType, fromEvent, setFrom, subtractFrom } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()export class BankAccountOpened { @field(String) readonly accountName: string; @field(Number) readonly initialBalance: number;
constructor(accountName: string, initialBalance: number) { this.accountName = accountName; this.initialBalance = initialBalance; }}
@eventType()export class BankAccountRenamed { @field(String) readonly newName: string;
constructor(newName: string) { this.newName = newName; }}
@eventType()export class FundsDeposited { @field(Number) readonly amount: number;
constructor(amount: number) { this.amount = amount; }}
@eventType()export class FundsWithdrawn { @field(Number) readonly amount: number;
constructor(amount: number) { this.amount = amount; }}
@fromEvent(BankAccountOpened)@fromEvent(BankAccountRenamed)@fromEvent(FundsDeposited)@fromEvent(FundsWithdrawn)export class BankAccount { @setFrom(BankAccountOpened, 'accountName') @setFrom(BankAccountRenamed, 'newName') name = '';
@setFrom(BankAccountOpened, 'initialBalance') @addFrom(FundsDeposited, 'amount') @subtractFrom(FundsWithdrawn, 'amount') balance = 0;}Set A Property From Event Context
Section titled “Set A Property From Event Context”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.
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);import io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.projections.FromEventimport io.cratis.chronicle.projections.SetFromimport io.cratis.chronicle.projections.SetFromContextimport io.cratis.chronicle.readModels.ReadModel
@EventTypedata class OrderPlacedForAudit(val customerName: String)
@ReadModel@FromEvent(OrderPlacedForAudit::class)data class AuditedOrder( @SetFrom("customerName", OrderPlacedForAudit::class) val customerName: String = "",
@SetFromContext(OrderPlacedForAudit::class, contextProperty = "occurred") val orderedAt: String = "")import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.projections.FromEvent;import io.cratis.chronicle.projections.SetFrom;import io.cratis.chronicle.projections.SetFromContext;import io.cratis.chronicle.readModels.ReadModel;
@EventTyperecord OrderPlacedForAudit(String customerName) {}
@ReadModel@FromEvent(eventType = OrderPlacedForAudit.class)class AuditedOrder { @SetFrom(propertyPath = "customerName", eventType = OrderPlacedForAudit.class) public String customerName = "";
@SetFromContext(eventType = OrderPlacedForAudit.class, contextProperty = "occurred") public String orderedAt = "";}defmodule MyApp.Events.OrderPlacedForAudit do use Cratis.Chronicle.Events.EventType, id: "order-placed-for-audit-v1"
defstruct [:customer_name]end
defmodule MyApp.ReadModels.AuditedOrder do use Cratis.Chronicle.ReadModels.ReadModel
alias MyApp.Events.OrderPlacedForAudit
defstruct [:id, :customer_name, :ordered_at]
from OrderPlacedForAudit, set: [ id: :event_source_id, customer_name: :customer_name, ordered_at: :occurred ]endimport { eventType, fromEvent, setFrom, setFromContext } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()export class OrderPlacedForAudit { @field(String) readonly customerName: string;
constructor(customerName: string) { this.customerName = customerName; }}
@fromEvent(OrderPlacedForAudit)export class AuditedOrder { @setFrom(OrderPlacedForAudit, 'customerName') customerName = '';
@setFromContext(OrderPlacedForAudit, 'occurred') orderedAt = new Date();}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.
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);import io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.projections.FromEventimport io.cratis.chronicle.projections.FromEveryimport io.cratis.chronicle.projections.SetFromContextimport io.cratis.chronicle.readModels.ReadModel
@EventTypedata class OrderPlacedForLifecycle(val customerName: String)
@EventTypedata class OrderShippedForLifecycle(val trackingNumber: String)
@ReadModel@FromEvent(OrderPlacedForLifecycle::class)@FromEvent(OrderShippedForLifecycle::class)data class OrderLifecycle( @SetFromContext(OrderPlacedForLifecycle::class, contextProperty = "occurred") val placedAt: String = "",
@SetFromContext(OrderShippedForLifecycle::class, contextProperty = "occurred") val shippedAt: String? = null,
@FromEvery(contextProperty = "occurred") val lastModified: String = "")import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.projections.FromEvent;import io.cratis.chronicle.projections.FromEvery;import io.cratis.chronicle.projections.SetFromContext;import io.cratis.chronicle.readModels.ReadModel;
@EventTyperecord OrderPlacedForLifecycle(String customerName) {}
@EventTyperecord OrderShippedForLifecycle(String trackingNumber) {}
@ReadModel@FromEvent(eventType = OrderPlacedForLifecycle.class)@FromEvent(eventType = OrderShippedForLifecycle.class)class OrderLifecycle { @SetFromContext(eventType = OrderPlacedForLifecycle.class, contextProperty = "occurred") public String placedAt = "";
@SetFromContext(eventType = OrderShippedForLifecycle.class, contextProperty = "occurred") public String shippedAt;
@FromEvery(contextProperty = "occurred") public String lastModified = "";}defmodule MyApp.Events.OrderPlacedForLifecycle do use Cratis.Chronicle.Events.EventType, id: "order-placed-for-lifecycle-v1"
defstruct [:customer_name]end
defmodule MyApp.Events.OrderShippedForLifecycle do use Cratis.Chronicle.Events.EventType, id: "order-shipped-for-lifecycle-v1"
defstruct [:tracking_number]end
defmodule MyApp.ReadModels.OrderLifecycle do use Cratis.Chronicle.ReadModels.ReadModel
alias MyApp.Events.{OrderPlacedForLifecycle, OrderShippedForLifecycle}
defstruct [:id, :placed_at, :shipped_at, :last_modified]
from OrderPlacedForLifecycle, set: [ id: :event_source_id, placed_at: :occurred ]
from OrderShippedForLifecycle, set: [shipped_at: :occurred]
from_every set: [last_modified: :occurred]endimport { eventType, fromEvent, fromEvery, setFromContext } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()export class OrderPlacedForLifecycle { @field(String) readonly customerName: string;
constructor(customerName: string) { this.customerName = customerName; }}
@eventType()export class OrderShippedForLifecycle { @field(String) readonly trackingNumber: string;
constructor(trackingNumber: string) { this.trackingNumber = trackingNumber; }}
@fromEvent(OrderPlacedForLifecycle)@fromEvent(OrderShippedForLifecycle)export class OrderLifecycle { @setFromContext(OrderPlacedForLifecycle, 'occurred') placedAt = new Date();
@setFromContext(OrderShippedForLifecycle, 'occurred') @field(Date) shippedAt?: Date;
@fromEvery(undefined, 'occurred') lastModified = new Date();}Map the event source identifier
Section titled “Map the event source identifier”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.
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);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).
Derived Context Values
Section titled “Derived Context Values”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: ...)].
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);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 A Value Only Once
Section titled “Set A Value Only Once”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:
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);defmodule MyApp.Events.MbSetOnceDocumentRevised do use Cratis.Chronicle.Events.EventType, id: "mb-set-once-document-revised"
defstruct title: ""end
defmodule MyApp.ReadModels.MbSetOnceDocument do use Cratis.Chronicle.ReadModels.ReadModel, types: [created: :datetime, last_revised: :datetime]
alias MyApp.Events.MbSetOnceDocumentRevised
defstruct original_title: nil, title: "", created_by: nil, created: nil, last_revised: nil
from MbSetOnceDocumentRevised, set_once: [ original_title: :title, created_by: {:caused_by, :subject}, created: :occurred ], set: [title: :title, last_revised: :occurred]endimport { eventType, Guid, setFrom, setFromContext } from '@cratis/chronicle';
@eventType()class DocumentRevisedForSetOnce { title = '';}
class SetOnceDocument { id: Guid = Guid.empty;
@setFrom(DocumentRevisedForSetOnce, { eventPropertyName: 'title', setOnce: true }) originalTitle = '';
@setFrom(DocumentRevisedForSetOnce) title = '';
@setFromContext(DocumentRevisedForSetOnce, { contextProperty: 'occurred', setOnce: true }) created = new Date(0);}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.
Choosing The Mapping
Section titled “Choosing The Mapping”| 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.