Skip to content

Setting Constant Values

The SetValue attribute sets a property to a compile-time constant whenever an event of a specified type occurs. Use it when a property should take a fixed value in response to an event — for example, setting a status flag, assigning a default category, or recording a fixed version number.

using Cratis.Chronicle.Events;
using Cratis.Chronicle.Keys;
using Cratis.Chronicle.Projections.ModelBound;
[EventType]
public record MbSetValueOrderPlaced(string CustomerName);
[EventType]
public record MbSetValueOrderCanceled;
public record MbSetValueOrder(
[Key]
Guid Id,
[SetFrom<MbSetValueOrderPlaced>(nameof(MbSetValueOrderPlaced.CustomerName))]
string CustomerName,
[SetValue<MbSetValueOrderPlaced>("active")]
[SetValue<MbSetValueOrderCanceled>("canceled")]
string Status);

When an OrderPlaced event occurs, Status is set to "active". When an OrderCanceled event occurs, Status is set to "canceled".

SetValue accepts any compile-time constant: strings, integers, longs, doubles, booleans, and enum values.

[EventType]
public record MbSetValueThingHappened;
public record MbSetValueThing(
[Key]
Guid Id,
[SetValue<MbSetValueThingHappened>("pending")]
string StatusLabel,
[SetValue<MbSetValueThingHappened>(42)]
int Priority,
[SetValue<MbSetValueThingHappened>(true)]
bool IsActive,
[SetValue<MbSetValueThingHappened>(3.14)]
double Score);

Apply the attribute more than once to respond to multiple event types:

[EventType]
public record MbSetValueSubscriptionStarted;
[EventType]
public record MbSetValueSubscriptionPaused;
[EventType]
public record MbSetValueSubscriptionCanceled;
public record MbSetValueSubscription(
[Key]
Guid Id,
[SetValue<MbSetValueSubscriptionStarted>("active")]
[SetValue<MbSetValueSubscriptionPaused>("paused")]
[SetValue<MbSetValueSubscriptionCanceled>("canceled")]
string State);
AttributeSourceWhen to use
SetValue<TEvent>(value)Compile-time constantThe value does not come from the event payload
SetFrom<TEvent>(property)Event propertyThe value comes from a property on the event

Combine both on the same read model when different properties come from different sources:

[EventType]
public record MbSetValueInvoiceIssued(decimal Amount);
[EventType]
public record MbSetValueInvoicePaid;
public record MbSetValueInvoice(
[Key]
Guid Id,
[SetFrom<MbSetValueInvoiceIssued>(nameof(MbSetValueInvoiceIssued.Amount))]
decimal Amount,
[SetValue<MbSetValueInvoiceIssued>("issued")]
[SetValue<MbSetValueInvoicePaid>("paid")]
string Status);