Skip to content

Model-bound projections: define mappings on a read model

A model-bound Chronicle projection defines how events build a read model on the read model type itself. In .NET, attributes describe the event mappings, so you can keep the view’s shape and update rules together without a separate IProjectionFor<T> class.

Start with convention-based mapping and add explicit attributes only where the event and read model use different names. That keeps the common case small while still making the exceptions visible.

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Keys;
using Cratis.Chronicle.Projections.ModelBound;
[EventType]
public record MbIndexAccountOpened(string Name, decimal InitialBalance);
[FromEvent<MbIndexAccountOpened>]
public record MbIndexAccountInfo(
[Key]
Guid Id,
string Name,
[SetFrom<MbIndexAccountOpened>(nameof(MbIndexAccountOpened.InitialBalance))]
decimal Balance);

View C# snippet source on GitHub

When Chronicle processes AccountOpened, [FromEvent<AccountOpened>] creates or updates an AccountInfo instance. [Key] marks its identifier. Name maps by convention because the event and read model use the same property name; Balance needs [SetFrom<TEvent>] because the event calls the value InitialBalance.

The .NET client discovers model-bound projection types from their annotations:

  • Class/record-level projection annotations such as FromEvent or NotRewindable, or event-sequence selection
  • Member mapping attributes such as SetFrom, AddFrom, or Join

No explicit marker is required on the type. [Passive] alone is not a discovery signal: it configures how an already-defined model is read, and can also configure a reducer model.

By default, a model-bound projection uses the read model’s fully qualified CLR type name as its identifier. Use [Projection(id: "...")] from Cratis.Chronicle.Projections on a class, record, or record struct to keep that projection identity when renaming the type or moving its namespace. When adding the attribute to an existing projection, use its previous identifier:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Keys;
using Cratis.Chronicle.Projections;
using Cratis.Chronicle.Projections.ModelBound;
[EventType]
public record StableIdentityAccountOpened(string Name);
// Before a rename, this read model was Accounts.AccountInfo.
// Keep its previous projection ID while renaming the CLR type.
[Projection(id: "Accounts.AccountInfo")]
[FromEvent<StableIdentityAccountOpened>]
public record StableIdentityRenamedAccountInfo([Key] Guid Id, string Name);

View C# snippet source on GitHub

An absent or empty attribute ID keeps the full-name default. The ID is not trimmed or normalized. Discovery, RegisterReadModel<T>() in client options, and runtime Projections.Register<T>() all use the same identifier. Callback-defined projections use it as their default too; an explicitly supplied callback ID takes precedence.

Keep model-bound annotations such as [FromEvent<TEvent>] when adding [Projection]. The latter supplies identity metadata; it does not define mappings or trigger discovery. [Projection] alone, or with only [Passive], does not make a model a projection. Its eventSequence argument configures fluent projections only; model-bound event-sequence routing still uses [EventSequence] and the existing event-store rules.

Different local projection owners cannot share an ID. Chronicle rejects competing fluent, model-bound, or explicit declarations before publishing the conflicting registration, identifying the ID and owner types. Registering the same model-bound read model explicitly as well as discovering it is still one projection; repeating that registration is allowed. Do not keep both the old and renamed owners locally.

A stable projection ID does not freeze the definition: Chronicle can still detect definition changes and apply its normal evolution or replay behavior. It also does not preserve the read model’s separate identifier or storage container name; a type rename can still change those defaults.

Start with the fields your query needs, then choose how events should populate them. Use direct mappings for values on the entity, joins for facts about related entities, and children or nested objects for structure inside the read model. Specialized builder features, such as fluent dynamic dictionary counters, do not all have attribute equivalents.

Choose the next page by the mapping you need:

  • Basic Mapping - SetFrom, AddFrom, SubtractFrom, SetFromContext
  • Set Constant Value - Set a property to a fixed value with SetValue
  • Clearing Values - Take a value away with ClearWith or a null SetValue
  • Convention-Based - Automatic property mapping with FromEvent (equivalent to AutoMap)
  • FromEvery - Update shared fields from handled events
  • FromAll - Subscribe to all event types without filtering
  • Counters - Increment, Decrement, Count
  • Children - Manage child collections
  • Nested Objects - Populate or clear a single object inside the model
  • Removal - Removing read models and children with RemovedWith, RemovedWithJoin
  • Joins - Joining with other events
  • Event Sequence Source - Reading from specific event sequences
  • Not Rewindable - Forward-only projections
  • Passive - On-demand projections
  • Variants - Mutually exclusive read model shapes for the same logical entity

Use a declarative IProjectionFor<T> when a mapping needs projection-specific scope that attributes on CLR members cannot describe. These independent examples focus on the mappings that need that scope.

Child or Nested Every-Mappings on Join-Only Events

Section titled “Child or Nested Every-Mappings on Join-Only Events”

Attributes on a child or nested CLR member cannot preserve an every-mapping for events handled only by a join in that scope. Model-bound generation expands those context mappings over local from events, so the join-only event’s timestamp mapping is lost.

Child every-mapping with a join-only event
using System;
using System.Collections.Generic;
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Projections;
[EventType]
public record ChildAuditOrderPlaced(string CustomerName);
[EventType]
public record ChildAuditItemAddedToOrder(Guid ProductId, int Quantity);
[EventType]
public record ChildAuditProductRenamed(string Name);
public record ChildAuditLine(Guid ProductId, int Quantity, string ProductName, DateTimeOffset LastUpdated);
public record ChildAuditOrder(string CustomerName, IEnumerable<ChildAuditLine> Lines);
public class ChildAuditOrderProjection : IProjectionFor<ChildAuditOrder>
{
public void Define(IProjectionBuilderFor<ChildAuditOrder> builder) => builder
.From<ChildAuditOrderPlaced>()
.Children(m => m.Lines, children => children
.IdentifiedBy(line => line.ProductId)
.From<ChildAuditItemAddedToOrder>(mapping => mapping
.UsingKey(e => e.ProductId)
.UsingParentKeyFromContext(c => c.EventSourceId))
.FromEvery(every => every
.Set(line => line.LastUpdated).ToEventContextProperty(c => c.Occurred))
.Join<ChildAuditProductRenamed>(join => join
.Set(line => line.ProductName).To(e => e.Name)));
}

View C# snippet source on GitHub

Here LastUpdated belongs to each line and tracks both ChildAuditItemAddedToOrder and ChildAuditProductRenamed. See declarative FromEvery and joining children.

A [Join<TEvent>] on a CLR member selects an event payload property, not a value from the joined event’s context. [SetFromContext<TEvent>] defines a local event mapping, not a join-context mapping.

Map the joined event's context
using System;
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Projections;
[EventType]
public record JoinAuditOrderPlaced(Guid ProductId);
[EventType]
public record JoinAuditProductRenamed(string Name);
public record JoinAuditOrder(Guid ProductId, string ProductName, DateTimeOffset ProductRenamedAt);
public class JoinAuditOrderProjection : IProjectionFor<JoinAuditOrder>
{
public void Define(IProjectionBuilderFor<JoinAuditOrder> builder) => builder
.From<JoinAuditOrderPlaced>()
.Join<JoinAuditProductRenamed>(join => join
.On(m => m.ProductId)
.Set(m => m.ProductName).To(e => e.Name)
.Set(m => m.ProductRenamedAt).ToEventContextProperty(c => c.Occurred));
}

View C# snippet source on GitHub

The join maps both the product name and the joined event’s occurrence time. See event context in children and joins.

Attributes bind to the CLR type’s members, not to each use of that type. One address type cannot carry different mappings for its billing and shipping roles; use separately scoped declarative mappings.

Reuse one address type with different mappings
using Cratis.Chronicle.Events;
using Cratis.Chronicle.Projections;
[EventType]
public record ScopedAddressOrderPlaced(string CustomerName);
[EventType]
public record ScopedAddressProductRegistered(string Name);
public record ScopedAddress(string Name);
public record ScopedAddressOrder(ScopedAddress? BillingAddress, ScopedAddress? ShippingAddress);
public class ScopedAddressOrderProjection : IProjectionFor<ScopedAddressOrder>
{
public void Define(IProjectionBuilderFor<ScopedAddressOrder> builder) => builder
.From<ScopedAddressOrderPlaced>()
.Nested(m => m.BillingAddress, nested => nested
.From<ScopedAddressOrderPlaced>(mapping => mapping
.Set(address => address.Name).To(e => e.CustomerName)))
.Nested(m => m.ShippingAddress, nested => nested
.From<ScopedAddressProductRegistered>(mapping => mapping
.Set(address => address.Name).To(e => e.Name)));
}

View C# snippet source on GitHub

Both properties use the same address type, but each nested scope selects its own event and source property. See multiple nested objects.

Generated Model-Bound Code: Representability Limits

Section titled “Generated Model-Bound Code: Representability Limits”

If you generate model-bound C# from a projection declaration, check the generated comments before switching to it. The generator keeps supported mappings and writes a Not expressible with model-bound attributes comment where attributes cannot preserve the declaration’s meaning. Compiling that code does not prove equivalent behavior. Keep the declaration or the generated declarative projection as the authoritative version when one of these comments appears.

Declaration feature Model-bound generation limit
Child every mapping from a payload property, such as Quantity = Quantity Child every-event expansion supports event-context and event-source-id mappings, not payload mappings. The unsupported mapping is commented rather than turned into a misleading attribute.
Child every mapping from a join-only event’s context Context mappings expand over the child’s local from events. An event subscribed only through a join cannot receive that context mapping through those attributes. The ordinary join payload mapping is retained.
One record type reused in incompatible projection scopes Attributes live on the record type, not on each use. The generator comments the conflicting record and omits its projection attributes rather than silently choosing the first scope.

Child Every-Event Mapping and a Join-Only Event

Section titled “Child Every-Event Mapping and a Join-Only Event”

This declaration excerpt assumes an Order read model with a Lines collection and the named events already registered. The child’s audit timestamp must update both for ItemAddedToOrder and for the join-only ProductRenamed event:

projection Order => Proof.Pdl.Order
from OrderPlaced
children Lines identified by ProductId
from ItemAddedToOrder key ProductId
every
LastUpdated = $eventContext.occurred
join Product on ProductId
with ProductRenamed
ProductName = Name

The generator can retain the ItemAddedToOrder context mapping and the ProductRenamed name join, but the generated child attributes do not preserve the timestamp update for that join-only event. It includes this comment in the generated output:

// Not expressible with model-bound attributes: every-mapping 'LastUpdated' for join event 'ProductRenamed' in children 'Lines'. Use the declarative projection.

Do not remove the comment and assume the remaining attributes are equivalent. Keep this mapping in the projection declaration or use a declarative projection. Likewise, keep child every-event payload mappings in the declaration rather than moving them to a root [FromEvery]: that changes which object owns the mapping. See every-event mappings and joins.

Suppose both BillingAddress and ShippingAddress use the same Address record with a Name property. This declaration excerpt requires different subscriptions and mappings for each use:

projection Order => Proof.Pdl.Order
from OrderPlaced
nested BillingAddress
from OrderPlaced
Name = CustomerName
nested ShippingAddress
from ProductRegistered
Name = Name

One set of attributes on Address cannot describe those two scopes independently. The generator omits the conflicting record’s projection attributes and emits:

// Not expressible with model-bound attributes: conflicting projection scopes for record 'Address'. Use the declarative projection.

Keep the scoped mappings in the declaration or declarative projection. If model-bound ownership is important, use distinct record types for the distinct roles and define their mappings explicitly. Reusing a record type is not inherently unsupported; the limitation is incompatible projection requirements on the same type, including incompatible descendant scopes.

Use model-bound attributes when keeping mappings beside the read model makes the update rules easy to follow. Move to fluent mappings when the definition needs more structure, or reducer code when state transitions are clearer in code. A self-reducing model is the default for new reducers. Choose how to build a read model works through these trade-offs before you commit to a style.

Fluent Projection:

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Projections;
[EventType]
public record MbIndexExplicitAccountOpened(string Name, decimal InitialBalance);
public class MbIndexExplicitAccountProjection : IProjectionFor<MbIndexExplicitAccountInfo>
{
public void Define(IProjectionBuilderFor<MbIndexExplicitAccountInfo> builder) => builder
.From<MbIndexExplicitAccountOpened>(_ => _
.Set(m => m.Balance).To(e => e.InitialBalance));
}
public class MbIndexExplicitAccountInfo
{
public string Name { get; set; } = string.Empty;
public decimal Balance { get; set; }
}

View C# snippet source on GitHub

Model-Bound Projection:

using Cratis.Chronicle.Keys;
using Cratis.Chronicle.Projections.ModelBound;
public record MbIndexExplicitMbAccountInfo(
[Key] Guid Id,
[SetFrom<MbIndexExplicitAccountOpened>(nameof(MbIndexExplicitAccountOpened.Name))] string Name,
[SetFrom<MbIndexExplicitAccountOpened>(nameof(MbIndexExplicitAccountOpened.InitialBalance))] decimal Balance);

View C# snippet source on GitHub

Fluent Projection (AutoMap is on by default):

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Projections;
[EventType]
public record MbIndexAutoMapAccountOpened(string Name, decimal Balance);
public class MbIndexAutoMapAccountProjection : IProjectionFor<MbIndexAutoMapAccountInfo>
{
public void Define(IProjectionBuilderFor<MbIndexAutoMapAccountInfo> builder) => builder
.From<MbIndexAutoMapAccountOpened>();
}
public class MbIndexAutoMapAccountInfo
{
public string Name { get; set; } = string.Empty;
public decimal Balance { get; set; }
}

View C# snippet source on GitHub

Model-Bound Projection with FromEvent:

using Cratis.Chronicle.Keys;
using Cratis.Chronicle.Projections.ModelBound;
[FromEvent<MbIndexAutoMapAccountOpened>]
public record MbIndexAutoMapMbAccountInfo(
[Key] Guid Id,
string Name, // Automatically mapped from MbIndexAutoMapAccountOpened.Name
decimal Balance); // Automatically mapped from MbIndexAutoMapAccountOpened.Balance

View C# snippet source on GitHub

In these examples, both approaches produce the same result. FromEvent gives the model-bound version automatic matching of event and read model property names, just as the fluent projection does by default.

Once the projection is defined, use IReadModels to read the view your application needs: