Domain modelling — aggregates, entities and value objects
All on one page: an aggregate, all in one — one aggregate whole, then the five principles. In practice: Tutorial Ch 2 · forms over an operation · testing the domain · cheat sheet. The rest of Rask.Data: storage — queries, conventions and the database · writing many rows. An app written before this? Upgrading to the domain way, step by step.
A Rask app's business code is its domain: aggregates, the entities they hold and the value objects their properties are. Every write is one of the aggregate's own methods, and everything else — the form that calls it, the save, the transaction, the check that a field is valid — is Rask's. There is one way to write it:
- A write is an aggregate method.
supply.Change(…),order.Ship(…). There is no service layer, no application service and no domain service: a rule that decides something is on the aggregate it is about, and another aggregate is read through its read face, never changed from here. - The aggregate is the transaction boundary. One aggregate is loaded whole, changed and saved in one transaction — the operation's generated entry does exactly that. A change to a second aggregate follows from a domain event; a save of two at once is the last resort.
- A value object carries its rule. Required, length, format and range are said once, in the type —
public sealed partial record DriverName(string Value) : Text(Value, MaxLength: 200);— and every form, every save and every message reads it from there (value objects). - Properties are value objects or typed ids.
DriverName,Litres,VehicleId— only abooland anenumstay primitive (strongly-typed ids). - A domain refusal is
Refuse. It names the field it is about, and a form shows it there (refusing an operation). - The form is the operation's.
Form.For(Supply.Update, id)is a form whose fields are the method's parameters, checked by the method's own rules as they are typed (a form over an operation). - No SQL and no provider API. The app names what it means — a bare
OrderBy,Db.Lock,.Covering(…)— and Rask writes it for SQLite, SQL Server and PostgreSQL alike (provider neutrality). - Tests run on SQLite in memory, a database per test, in parallel —
TestDatabase.Start<T>(),Test.Refuses,Test.Concurrently(testing a model).
Included in
Rask.Server, so there is nothing to install. The value-object bases (Rask.Values) are theRaskpackage's, so a library onRaskalone declares its values the same way.
The whole of it
public readonly partial record struct ProductId(Guid Value); // a typed id: one line
public sealed partial record ProductName(string Value) : Text(Value, MaxLength: 200); // a value object: one line
public sealed partial record UnitPrice(decimal Value) : Number(Value, Min: 0, Scale: 2);
public sealed class Product : Aggregate<ProductId>, IHasTimestamps, IVersioned, IDeletable
{
public ProductName Name { get; private set; }
public UnitPrice Price { get; private set; }
public bool Discontinued { get; private set; }
private static Product Create(ProductName name, UnitPrice price) => // the factory: its entry is Product.Create(…)
new() { Id = ProductId.Create(), Name = name, Price = price };
public void Reprice(UnitPrice price) // an operation: Product.Reprice(id, version, …)
{
Refuse.When(Discontinued, () => Price, "A discontinued product keeps its last price.");
Price = price;
}
public void Discontinue() => Discontinued = true;
}
That is the whole declaration — no partial. The build turns it into a mapped table, a read face to query, and a
static entry per operation that runs it as one write:
var product = await Product.Create(ProductName.Create("Anvil"), UnitPrice.Create(9.90m)); // the factory, saved
await Product.Reprice(product, UnitPrice.Create(12.50m)); // Find(id, version) → Reprice → Save()
var cheap = await Product.Where(p => p.Price.Value < 10).OrderBy(p => p.Name); // the read face, in SQL
A page binds a form to the operation itself — its fields are the parameters, checked by UnitPrice's rule and by
the Refuse in Reprice as they are typed, and saved through the entry:
Form.For(Product.Reprice, id)[f => [
Ui.Field.Bind(() => f.Price).Label("Price"),
Ui.Button.Primary.Submit["Save"],
]]
And a test proves the rule on SQLite in memory, a database of its own:
[Fact]
public async Task A_discontinued_product_keeps_its_price()
{
await using var database = await TestDatabase.Start();
var id = await Product.Create(ProductName.Create("Tea"), UnitPrice.Create(9.90m));
var product = (await Product.Find(id))!;
product.Discontinue();
await product.Save();
var refusal = await Test.Refuses(() => Product.Reprice(id, product.Version, UnitPrice.Create(5m)));
refusal.Only("Price");
}
TestDatabase.Start() is a SQLite database in memory for this test alone (TestDatabase.Start<AppDbContext>() for an
app with a context of its own), so tests run side by side; testing a model has the rest.
Note p.Price.Value < 10: the read face holds the value objects the aggregate holds — p.Price is the
UnitPrice itself, and a value object of several values is itself too — and a query reads what one holds straight
from its column (the read face).
Generated, never reflected. A source generator finds every aggregate at build time and hands it to
RaskAppDbContext; no assembly is scanned and no method is found by name, so a trimmed publish cannot quietly drop
an aggregate and leave you a missing table with a green build.
Here is a whole model running — a Note aggregate, queried with Note.OrderByDescending(…), renamed through
Form.For(Note.Rename, id) and searched with Note.Search, in a SQLite database that lives in this browser tab and
survives a reload:
Aggregates, entities and value objects
Rask.Data speaks domain-driven design, and the base class you derive from says which of the three a type is. Two
entities are equal when they are of the same type with the same Id — two loads of one row are the same entity —
and one with no id yet (an integer key before its insert) is equal only to itself:
| You declare | What it is | What it gets |
|---|---|---|
Aggregate<TId>, plus the trait interfaces it names |
A consistency boundary: the thing you load, change and save as one | Its table, the static writes, its read face, domain events, a generated Create (and Update when IUpdatable) where it writes none — and the traits it names: timestamps, Version, a Delete |
Entity<TId> |
Something with identity inside an aggregate, such as an order's line | Its table, and the rows its parent's form carries (below); it is loaded, saved and deleted with its aggregate |
a record, a record struct, or a class on ValueObject it holds |
A value object: Money, Address, Email |
Columns on the owner's row (below) |
Aggregate<TId> derives from Entity<TId>, and the framework's columns are the ones the class says. They are
real properties with private setters, so a screen can show them and a query can sort by them, while only the
framework writes them:
| Property | Declared on | Effect |
|---|---|---|
Id |
Entity<TId> |
The key. A Guid (or a typed id over one) is assigned in the factory — the default; an integer (or a typed id over one) is the store's identity. A [Key] on another member is RASK143. |
CreatedAt, UpdatedAt |
Entity<TId> |
With IHasTimestamps (or IHasCreatedAt / IHasUpdatedAt for one). Stamped (UTC) on insert and on every update. |
Version |
Aggregate<TId> |
With IVersioned. The optimistic-concurrency token, bumped on every update. |
DeletedAt |
Aggregate<TId> |
With ISoftDeletes. The generated Delete stamps it instead of removing the row. |
var recent = await Product.OrderByDescending(p => p.CreatedAt).Take(10);
Aggregate<TId> also carries the domain-events buffer: Raise(…) inside a method, beside the XCreated/XUpdated/
XDeleted every save raises. After the save commits, each static Task On(E e) hears it — from the outbox,
which stored it in the same transaction, or in memory when it says [Immediate] (domain events).
Aggregates declare no constructor. The implicit parameterless one is what EF Core materialises rows
through, and what a generated Create starts from before it sets each
property. Domain creation goes in a static factory, as Product.Create does above; a constructor that takes
arguments leaves the aggregate with no generated Create. Nor is a private Product() { }
needed to keep new out: new Product() anywhere outside Product is an error that names its factories
(RASK107), and the empty private constructor is reported as one Rask does not need,
with a quick-fix that deletes it (RASK149).
State changes through the type's own methods. A public set, a hand-written public init or a public
mutable field on an aggregate, an entity or a value object one of them holds is a build error
(RASK084). EF Core and the generated writes both work through private setters, so
nothing needs a public one.
{ get; } or { get; private set; } says who changes it. { get; private set; } is a value a business step of
the type changes — Price above, which Reprice sets, or Name, which the factory's initializer sets. { get; } is
a value nothing in the type ever assigns after it is built: the fields of a data-shaped aggregate
that only its generated Create writes, a reference a constructor of a child sets once. Rask maps the two the same — EF Core
loads, saves and change-tracks a { get; } auto-property through the compiler's backing field, a generated Create
reaches the field through an [UnsafeAccessor], and the column, its name and its type are the ones
{ get; private set; } had, so moving between them is no migration. That holds for a string, a number, an enum, a
nullable one, a typed id, a value object, a BelongsTo and a HasMany alike; an expression-bodied property
(Display => …) stays computed, never a column.
public sealed class Destination : Aggregate<DestinationId>, IDeletable
{
public DestinationName Name { get; } // only the generated Create sets it: { get; }
public CountryCode Country { get; }
public bool Closed { get; private set; } // Close() changes it: { get; private set; }
public void Close() => Closed = true;
}
A { get; private set; } that nothing in the type assigns outside its constructors is a suggestion to drop the setter
(RASK166), whose Fix all converts a whole project. The other way round is the compiler's:
assigning a { get; } property in a method or a factory's initializer is CS0200 — give it private set, since a
step of the type now changes it.
Value objects
A value object is its values: two with the same values are the same. Any composite an entity holds that is not itself an entity is one, and its values become columns on the owning row: one that holds a single value is that value's column, and one that holds several is an EF Core complex type.
Declared from a base record
A value object is declared from the base record of what it holds, with its rules as the base's arguments, and is
checked as it is made — no instance exists that its rules refuse. Rask writes the rest. The bases — Value, Text,
Number, Integer, Day, Range and their Problem — are the Rask package's (namespace Rask.Values), and so is the
generator that writes Create, TryCreate, CreateOptional and Check: a browser app or a component library on
Rask alone, with no data layer, declares its values the same way with a using Rask.Values;. Rask.Data maps them to
columns and imports the namespace for you, with Range aliased over System.Range:
public sealed partial record DriverName(string Value) : Text(Value, MaxLength: 1000);
public sealed partial record ChipCode(string Value) : Text(Value, MaxLength: 1000, Trim: false);
public sealed partial record Vin(string Value) : Text(Value, MinLength: 17, MaxLength: 17, Upper: true);
public sealed partial record TaxNumber(string Value) : Text(Value, Pattern: @"^\d{8}-\d-\d{2}$", Message: Texts.TaxNumberForm);
public sealed partial record Litres(decimal Value) : Number(Value, Min: 1, Scale: 2);
public sealed partial record UnitPrice(decimal Value) : Number(Value, Min: 0, Scale: 9, Round: true); // computed: rounded, not refused
public sealed partial record Pieces(long Value) : Integer(Value, Min: 0, Max: 1000);
public sealed partial record InvoiceDay(DateOnly Value) : Day(Value, NotAfterToday: true);
public sealed partial record FuelingMoment(DateTime Value) : Moment(Value, NotAfterNow: true);
public sealed partial record KmRange(int Start, int End) : Range(Start, End, Strict: true); // End > Start
public sealed partial record ChipPeriod(DateTime From, DateTime? To) : Range(From, To); // no end: open
public sealed partial record RefundMonths(int From, int To) : Range(From, To, Min: 1, Max: 12);
public sealed partial record KmReading(int StartKm, int EndKm) : Range(StartKm, EndKm, Strict: true,
Message: "A záró km-nek nagyobbnak kell lennie a kezdőnél."); // its own words
public sealed partial record Opening(DateOnly? Date, decimal? Quantity) : Value
{
protected override IEnumerable<Problem> Rules()
{
if (Date is null != Quantity is null) yield return Problem.At(Quantity, "Both or neither.");
}
}
public sealed class Delivery : Aggregate<Guid>
{
public DriverName Driver { get; private set; } // no made-up value, no null! (RASK150): Start sets it (RASK198)
public Litres Fuel { get; private set; }
public KmRange Km { get; private set; }
public static Delivery Start(string driver) => new() { Driver = DriverName.Create(driver, nameof(Driver)), Fuel = Litres.Create(1), Km = KmRange.Create(0, 1) };
public void Fill(decimal litres) => Fuel = Litres.Create(litres, nameof(Fuel));
public void Drive(int start, int end) => Km = KmRange.Create(start, end, nameof(Km));
}
| Base | Holds | Rules |
|---|---|---|
Text |
string Value |
filled (Required: false: an empty text is the value ""), MaxLength, MinLength, Pattern, Trim (on by default), Upper (kept in capitals) or Lower (in small letters), its own Normalize (tidies the text) |
Number |
decimal Value |
Min, Max, Scale (most decimal places), Precision (most digits), Round (to the scale instead of refusing) |
Integer |
its own int or long Value |
Min, Max |
Day |
DateOnly Value |
NotBefore, NotAfter, NotAfterToday (today is Clock.Today) |
Moment |
an instant, always UTC: .Utc (a DateTimeOffset at offset 0) |
NotBefore, NotAfter (in UTC), NotAfterNow (now is Clock.Now); .Day is its DateOnly in Clock.Zone, FromWall(local[, zone]) makes one from a clock's local time |
Range |
its own two members | the end not before the start (Strict: after it), Min and Max for both ends; a null end is open |
FileValue |
Upload File — an uploaded file in hand |
given and not empty, MaxSize (bytes: 10.Megabytes), Types (extensions: [".pdf", ".jpg"]), and bytes that start as that type's do (a file the row holds) |
Value |
its own members | whatever Rules() yields — Problem.At(member, message) or Problem.Whole(message); with ONE member it is a one-value value object: one column, asked on its field, refused under it |
Every base but Value takes a Message: what a value that breaks any rule declared there is told, in the app's
own words, said once however many rules it breaks (a Range says it under each end it is about) — instead of the
framework's sentence for each, from Rask's strings catalog. A text left blank is still told it is required.
Kinds of text: Email, Phone, Url, Password, Multiline
Five bases are a Text that also knows what kind of text it holds — its format rule and the input it is typed into.
Each takes Text's arguments (MaxLength, MinLength, Message, Trim, Upper, Lower, Required; Password and
Multiline a Pattern too), is made, stored and asked exactly as a Text, and gives the control bound to it in a
form over an entry what the matching DataAnnotations attribute would give a plain string:
public sealed partial record ContactEmail(string Value) : Email(Value, MaxLength: 200);
public sealed partial record ContactPhone(string Value) : Phone(Value);
public sealed partial record Homepage(string Value) : Url(Value, Required: false);
public sealed partial record SignInPassword(string Value) : Password(Value, MinLength: 8);
public sealed partial record ChosenPassword(string Value) : Password(Value, MinLength: 12, New: true);
public sealed partial record Remark(string Value) : Multiline(Value, MaxLength: 4000);
Ui.Field.Bind(() => m.Email) // <input type="email" maxlength="200" autocomplete="email">, the email rule on change, on submit, on save
| Base | Its rule | Column | A bound control | Attribute path |
|---|---|---|---|---|
Email |
[EmailAddress]'s own check: one @, neither first nor last |
254 unless declared | type="email", autocomplete="email" |
[EmailAddress] |
Phone |
[Phone]'s own check |
32 unless declared | type="tel", inputmode="tel", autocomplete="tel" |
[Phone] |
Url |
an absolute http or https address ([Url] also lets ftp and anything that only starts like one through) |
2048 unless declared | type="url" |
[Url] |
Password |
its lengths, its pattern and its Rules(); not trimmed unless Trim: true |
— never stored | type="password", autocomplete="current-password" (New: true: "new-password"), its value never written by the server |
[DataType(DataType.Password)] |
Multiline |
as Text |
as declared | Ui.Field.Bind draws a Ui.Textarea |
[DataType(DataType.MultilineText)], [UIHint("MultilineText")] |
The two paths give the identical FieldShape (Input, AutoComplete, InputMode, Hint, the lengths), so a
control cannot tell them apart; the value-object path also checks the rule wherever the value is made — a command,
a job, an import — not only where a form posts it. The format messages are the strings catalog's
(ValidationEmail, ValidationPhone, ValidationWebAddress), or the record's own Message.
A password is input only. Its ToString() and its debugger view say ••••, so a log line or $"{password}"
never shows it; read .Value where it is checked or hashed. An aggregate or entity that stores one — directly, in a
value object or in a list — is RASK175 (store the hash), and the generated read face leaves
it out; a query's or a command's result, a subscription's item or an event that carries one is
RASK176. A command that takes one in — record SignIn(ContactEmail Email, SignInPassword Password) : ICommand<Token> — is what it is for.
The record's positional parameter Value is the base's get-only Value (so name with { Value = … } does not
compile); a Range or Value record keeps its own typed members. The constructor asks the rules and throws a
RaskValidationException — one failure per problem, under the member it names — and the generated half adds,
over the primary constructor's parameters:
X.Create(…, field)— the same, withfieldin front of each failure:KmRange.Create(10, 5, "Km")is refused underKm.End,DriverName.Create(text, "Driver")exactly underDriver, so a form whose submit lets it through shows each message there. Thefieldis optional.X.TryCreate(…, out var x, out var problems)— the answer without an exception.X.CreateOptional(…, field)— nothing when nothing was given (text: only blanks), a required failure under each member left empty when only some were (KmRange.CreateOptional(5, null, "Km")→Km.End), otherwiseCreate.X.Parse(text, format, field)andX.TryParse(text, out var x)/X.TryParse(text, format, out var x)— aMomentor aDayread from text, for a file or an API: culture-invariant, ISO 8601 unless an exactformatis named (FuelingMoment.Parse("2026.11.23. 08:35", "yyyy.MM.dd. HH:mm")), read as the UTC instant it names. A moment written with its offset (2026-11-23T08:35:51+01:00,…Z) is that instant, and one without is a local time of the app's zone (Clock.Zone), made an instant asFromWallmakes one — across summer time too; aDayis the day of a moment on the calendar ofClock.Zone(2026-11-23T23:30:00Zis the 24th in Budapest). Text that is no moment throws aFormatException, a moment a rule refuses theRaskValidationExceptionCreatethrows (underfield);TryParseanswers false for both. A record declaring aParseorTryParseof its own keeps it.
new KmRange(…) would throw without naming the field, and a with copies a value past its rules:
RASK127 refuses both outside the type, tests included, and its quick-fix writes the
Create (km with { End = 5 } → KmRange.Create(km.Start, 5)). It must be sealed partial
(RASK129), since Rask writes its other half. Two values are equal when they are of the
same type and hold the same values; a one-value record's ToString() is its value — $"{chip}" is C-17, never
FuelingChip { Value = C-17 }. Every base writes it culture-invariant — Number and Integer as
1234.5 on every machine, never 1234,5, a Day as ISO 8601 2026-01-31 and a Moment as 2026-01-31T14:05:00: it is the value's text, and showing it to a reader is the UI's and
Format's job. One declared straight from Value (FuelingChip(string Value) : Value) gets it generated the same
way; a ToString the record declares itself is kept.
Required: false lets a text be empty: public sealed partial record FuelingChip(string Value) : Text(Value, MaxLength: 1000, Required: false); makes FuelingChip.Create("") (or only blanks) the value "" with no problem, while
a filled one is still held to its lengths and its pattern. A form field of it is neither
refused nor announced as required when left empty, and saves ""; CreateOptional("") is still nothing.
Upper: true keeps the text in capitals, culture-invariant ("wvwzzz1jzxw000001" → "WVWZZZ1JZXW000001",
"árvíztűrő" → "ÁRVÍZTŰRŐ"): after the trim and before the lengths and the pattern, so a Pattern is written
for the capitals. A stored value is loaded as it was stored. A bound input draws what is typed in capitals (the
text-transform only); the text is put in capitals when it is made. Lower: true is the same in small letters
("Ada@Example.COM" → "ada@example.com", an Email(Value, Lower: true)); a text is kept in one case, so declaring
both throws as the value is made.
A text that tidies itself: Normalize
A text that arrives with marks around it — a card number a fuel card file writes as ="AB12", a tax number with its
spaces — tidies itself: the record overrides Normalize, and every way the value is made keeps the same text. Like
Rails' normalizes, it is the value's own rule, written once beside its other rules:
public sealed partial record CardNumber(string Value) : Text(Value, MaxLength: 50, Upper: true)
{
protected override string Normalize(string text) => text.Replace("=", "").Replace("\"", "").Replace("'", "");
}
CardNumber.Create(" ='ab12' "); // "AB12"
- The order is fixed: trim →
Normalize→Upper/Lower→ the lengths and the pattern.Normalizeis given the trimmed text (as given withTrim: false), so the rules check what is kept:MaxLength: 4takes"='ab12'". - A text it leaves blank is no text:
CreateOptional("''")is null,Create("''")is refused as required, and aRequired: falsetext is"". - Every door tidies it:
Create,TryCreate,CreateOptional,Check, a form's rule and a JSON read (the bare value goes through the constructor). A stored value is loaded as it was stored, never tidied again. - A lookup tidies its parameter the same way:
cards.Where(c => c.Number == CardNumber.Create(raw))finds the row stored from="AB12"— there is no hand-writtenNumberOf(raw)helper beside the type to keep in step. - A form shows the kept text once the reader leaves the field. No browser can run the record's C#, so a bound
field is tidied where its handler runs (the server, or the WASM app): on the change — never at a keystroke — a field
holding the value object holds the made value, a text field of a form over an entry
holds the tidied text, and the next render shows it.
UpperandLowerare also drawn as the reader types; aPatternis not told to the browser for a tidied (or cased) text, since the browser would check the text as typed.
It is called from the constructor, so it reads only the text it is given, never a member of the record.
Round: true rounds a number to its Scale instead of refusing its extra digits — half away from zero, as SQL
Server rounds what it stores — before the bounds and the precision are checked. It is for a number nobody typed: a
unit price or a share of a total computed in the domain, which used to be rounded silently by the column and would
otherwise be refused for its fourteenth decimal. UnitPrice.Create(1.0000000005m) holds 1.000000001m. A Round
with no Scale throws as the value is made.
A one-value record of an ordered value orders like it. Over a number, a whole number, a day, a moment or a
text (any value that is IComparable of itself) the generated half makes the record IComparable and gives it <,
>, <= and >= against its own type: fuelings.OrderBy(f => f.Moment) sorts a list as the database sorts the
column, and f.Moment >= since reads as it means — and translates on the write model, see
value objects of any shape. A record that writes its own CompareTo or operators keeps them.
An enum is a one-value record over Value: public sealed partial record FuelKind(Fuel Value) : Value;, with
any rule of its own in Rules(). It is one column of the enum's own type — EF Core's enum-to-number, or whatever
HasConversion the app gives the enum — a form over an entry that takes it holds Fuel? Fuel, and a control bound to it is
offered the enum's members, labelled by their [Display(Name)], as for a bare enum.
A test makes one as the app does: Vin.Create("WVWZZZ1JZXW000001") — see testing.
A Moment is an instant, and always UTC — in storage and in code. .Utc is the one value it holds (a
DateTimeOffset at offset 0 — what every database keeps, and what two moments are equal, ordered and subtracted by);
there is no wall-clock .Value to compute with. The DateTime it is made from is read as UTC (an unspecified one
too; one of DateTimeKind.Local is converted from the machine's zone), so FuelingMoment.Create(Clock.Now.UtcDateTime)
is now. Local time appears at the two edges only: display — Format.Moment(m), the Ui tables, facts and pickers
show it on the clocks of Clock.Zone — and ingest — FromWall(local[, zone]). .Day is its calendar day in
Clock.Zone (what a report groups by), and .WallIn(zone) the one explicit local DateTime, for a protocol. A bound
field of one draws a Ui.DayAndTime, in Clock.Zone, ending now for NotAfterNow. See Moment and Day.
A stored value is loaded, never re-checked. EF Core builds what a row holds without asking the rules — a row
stored before a rule was tightened still loads, a tracked entity holding one still saves, and a query that fails on
a row leaves the next Create checking again. Only what the code makes goes through them.
Over remote dispatch it travels as what it holds. A command, query, event or result crossing between the
browser and the server (Rask.Cqrs.Client/Rask.Cqrs.Server) may carry one: a one-value record is its bare value
on the wire — "ABC-123", 12.5, never {"value":"ABC-123"} — and a Range or Value record an object of its
members. The server rebuilds what a browser sent through the generated Create with its rules asked, so no handler is
given a value they refuse: the request is answered 400 with each refusal under its field (Driver.Name). The
browser rebuilds what the server answers as a loaded row is, unchecked, so a value stored before a rule was
tightened still reaches the page. See the wire codecs.
In System.Text.Json it is its value too. A read row an endpoint returns, an API body, a job's stored command or
an outbox message writes a one-value value object — declared from Text or one of its kinds (Email, Phone,
Url, Multiline), Number, Integer, Day, or Value over one member — as the value it holds: "Ada",
12.5, "2026-11-28", never {"Value":"Ada"}, the same as the wire codecs and the generated API client. The value
object generator gives each record its own [JsonConverter] (System.Text.Json reads none off a base type) — no
reflection, so it trims and runs AOT. Read, the value is made through the record's constructor, so its rules are
asked; the object form written before, {"Value":"Ada"} in any casing, is still read. A Password (input only),
a generic record, one over a nullable member and one that names its own [JsonConverter] keep their object form;
a Moment is its instant.
The column takes what the value object declares, read from its base arguments when the app is compiled —
constants included (Text(Value, MaxLength: Limits.Name)), and without building an instance: a Text(Value, MaxLength: 1000) is HasMaxLength(1000), a Number(Value, Scale: 2, Precision: 9) is HasPrecision(9, 2) (a
scale alone keeps EF Core's precision of 18). A one-value record is one column; a Range or Value record is a
complex type, one column per member. An attribute on the property — [MaxLength], [StringLength],
[Precision] — is the app's word for that one column and wins over the value object's, and the entity's own
Configure runs after both and has the last word. RASK128 warns when either gives the
column a length or precision other than the value object's, since a value the rule accepts would then not fit.
Every save asks the attribute like any other ([Required] included, which also makes the column NOT NULL), so a
form's dry run and every entry ask it beside the value object's rule: the tighter of the two refuses.
A value object held inside another keeps its own column shape. Opening(DateTime Date, Amount Quantity) : Value
with Amount : Number(Value, Scale: 16, Precision: 32) stores Start_Quantity as decimal(32,16) — the Amount
says so, and no HasPrecision in Configure is needed; a plain decimal Quantity member has no rules to read, so
it keeps EF Core's default.
An optional complex value is null when its row has none. public Opening? Start { get; private set; } is an EF
Core optional complex property: every column under it is nullable, a row with no opening holds NULL in all of
them and loads Start as null, and the read face's Start is the same Opening?, null for such a row. When a member is not nullable, that one column tells a
row with an opening from one without. When every member is optional — Opening(DateTime? Date, decimal? Quantity)
held as Opening?, the shape a legacy table with two nullable columns has — every column NULL is none: a row
holding only a date, or only a quantity, loads as that Opening, a row holding neither loads as null, and
Where(p => p.Start == null) asks that every column is NULL. No column is added for it, so a schema another tool
made is read as it is. An Opening(null, null) saved is therefore read back as null: a value whose members are all
empty is no value. EF Core alone refuses such a property (it asks for a discriminator column); every
RaskDbContext holds it on any relational provider, and UseRaskSqlite, UseRaskSqlServer and UseRaskPostgres
hold it on a plain DbContext too. Don't start it from a placeholder (= Opening.None, which
RASK150 flags): leave it null.
An empty text, or nothing? A nullable text left empty is stored as nothing: CreateOptional turns blank text
into null, and the column holds NULL. A table whose rows tell '' from NULL — an older client that refuses
NULL, a report that counts the two apart — keeps them apart with KeepEmpty in the aggregate's Configure:
public VatNumber? VatNumber { get; private set; }
public string? Remark { get; private set; }
public static void Configure(EntityTypeBuilder<Company> b)
{
b.KeepEmpty(c => c.VatNumber); // a string, or a value object of one text
b.KeepEmpty(c => c.Remark);
}
A field left empty, or emptied, then writes '' — the value object holding it, whose rules are not asked of an
empty text — and a new row starts with ''. A row that holds NULL there and is saved with the field still empty
keeps its NULL, so a save that changes nothing writes nothing; a filled field still answers to every rule. A
stored '' loads as the value object holding it and fills an edit form's field with "". The writes read the call from the
aggregate's own static Configure, as they read IsUnique — written anywhere else it is
RASK165; on a member not stored as text it throws when the model is built.
Columns named before the value object existed. EF Core names a complex type's columns Km_Start and Km_End.
A table whose columns were already StartKm and EndKm — read by reports and raw SQL — keeps them with one line in
the entity's Configure:
public KmRange Km { get; private set; }
public static void Configure(EntityTypeBuilder<DeliveryNote> b) =>
b.Columns(n => n.Km, "{Member}Km").Columns(n => n.Trip, "{Member}Date"); // StartKm, EndKm; StartDate, EndDate
{Member} is each member of the value object; a value object nested inside it keeps EF Core's naming below the
pattern (ReadingKm_Value). The read face holds the value object itself and reads it from the same columns —
DeliveryNote.Where(n => n.Km.Start >= 100) — because it mirrors what the write model decided. A
pattern without {Member}, or a member that is not a value object of several members, throws as the model is built.
A form over an entry is unchanged: f.Km.Start and f.Km.End.
A form over an entry holds a one-value record as its value (string? Driver):
it asks the same rules under the field and gives a text input the MaxLength/MinLength as its
maxlength/minlength (its field shape, X.__Field — see forms validation), and the entry
asks them before anything is written — each message in the reader's language from Rask's strings catalog. A
parameter that is not nullable is required; a nullable one may be left empty.
An aggregate that stores a bare string, number, moment or Guid gets RASK130 — a
suggestion, and a warning under <RaskStrict> — pointing at the value object that would carry its rules.
A value object of any other shape — below — holds no rule of its own: a public static Validate beside its
value is never asked (RASK132).
Value objects of any shape
One an abstract base declares is mapped the same way, at any depth, on every aggregate deriving from it: each
concrete aggregate is its own table holding the base's columns, and its read face and generated Create carry them too.
A generic base (Filing<TSelf> where TSelf : Filing<TSelf>) is no different: VatReturn : Filing<VatReturn> holds
the base's children and collections of values behind its private fields as its own.
The base itself is never an entity of the model.
It must compare by value, or the build says so (RASK105). A record or a
record struct already does, and needs nothing else. A plain class derives from ValueObject and names the values
that make it the same:
public sealed class Address : ValueObject
{
private Address() { } // a value object's own guard: no rule keeps `new Address()` out
public string Street { get; private set; } = "";
public string City { get; private set; } = "";
public static Address At(string street, string city) => new() { Street = street, City = city };
protected override IEnumerable<object?> EqualityComponents()
{
yield return Street;
yield return City;
}
}
Unlike an aggregate, a plain-class value object keeps its private parameterless constructor when it has a factory:
EF Core builds it through that constructor either way, but RASK107 guards only aggregates
and entities, so the constructor is what keeps an empty new Address() out. A record declared from one of Rask's
bases needs neither — RASK127 guards its new.
A record that compares some other way says so in its own Equals — the language uses it for == too:
public sealed record Email(string Value)
{
public bool Equals(Email? other) =>
other is not null && string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase);
public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value);
}
The database may disagree with C#. A string record compares ordinally and case-sensitively, while SQL Server's
default *_CI_* collation — and a unique index under it — treats "Abc" and "abc" as one. Compare the value
object the way its column does, as Email above does.
public sealed record Money(decimal Amount, string Currency);
public sealed record Email(string Value);
public sealed class Customer : Aggregate<Guid>, IUpdatable
{
public Money CreditLimit { get; private set; } = new(0m, "EUR"); // CreditLimit_Amount, CreditLimit_Currency
public Email Email { get; private set; } = new(""); // one column: Email
}
A one-value value object is one column named after the property, so Email Email is stored as Email, and a
form over an entry holds it as its value, string? Email. A value object with
several values is prefixed by the property, and a form holds it as a group of fields (f.CreditLimit.Amount).
Declare it nullable and it is optional — a class or a struct alike:
public sealed partial record Percent(decimal Value) : Number(Value, Min: 0, Max: 100);
public readonly record struct Grade(int Value);
public Email? Backup { get; private set; } // nullable column Backup, form field string? Backup
public Percent? Discount { get; private set; } // nullable column Discount, form field decimal? Discount
public Grade? Rank { get; private set; } // nullable column Rank, form field int? Rank
An empty field is stored as NULL and is not put to the rule; a filled one is asked Percent's rules by the form
and by Create/Update, and the read face holds Percent? Discount. A value object that checks a rule is a
sealed record: a struct has a default that no constructor checked, so Grade holds no rule. A nullable struct of several
values (Money? over a record struct) is not unwrapped: no form field holds it, and its
mapping is yours to write in Configure.
That one column is an ordinary scalar column with a conversion — the value object goes in and out through its one value — so everything a column can have, it can have, configured on the property itself:
public static void Configure(EntityTypeBuilder<Customer> builder)
{
builder.Property(c => c.Email).HasMaxLength(255);
builder.HasIndex(c => new { c.Email, c.TenantId }).IsUnique("This address is already registered.");
}
The unique rule's failure names the field Email — the form's own name for it — not Email.Value. The value
object is rebuilt through the constructor that takes its value, or, for the private shape, a parameterless
constructor and its property; both may be private.
A query on the aggregate reads the value as its column. .Value is the column itself, typed as the value — on
SQL Server, SQLite and PostgreSQL alike, with the column's own store type and no CAST — so a write-side query
filters, sums and sorts by it; and a value object of one ordered value (a number, a whole number, a day, a moment,
a text) is generated IComparable with <, >, <= and >= against its own type, so the whole value compares and
sorts too, in the database and in a list:
// on the read face the value object is itself, and its value reads the column as it does here
await Customer.Where(c => c.Email.Value.StartsWith("ada@")).OrderBy(c => c.Email);
// on the write model (plain EF Core over the aggregate) the value inside translates…
await db.Set<Transaction>().Where(t => t.Quantity.Value > 0).SumAsync(t => t.Quantity.Value, ct);
// …and so does the whole value: compared, ordered, set by ExecuteUpdate
await db.Set<Fueling>().Where(f => f.Moment >= since).OrderBy(f => f.Moment).ThenBy(f => f.Id).ToListAsync(ct);
await db.Set<Fueling>().Where(f => f.Id == id).ExecuteUpdateAsync(s => s.SetProperty(f => f.Moment, moment), ct);
// …and outside the database it orders the way the column does
fuelings.OrderBy(f => f.Moment);
Only Rask's own conversion is read through: a column the app maps with a converter of its own stores what that
converter writes, which need not be the value, and .Value there is still "could not be translated". Two value
objects of different types are never compared — the operators take the one type.
The same holds inside another value object. Currency in record Money(decimal Amount, Currency Currency)
is a converted scalar column of Money — Price_Currency, the column it always was — which is what lets EF Core
hand it to Money's constructor. Its facets go on that property:
builder.ComplexProperty(c => c.Price).Property(m => m.Currency).HasMaxLength(3);
One shape stays out of reach: a value object built through its constructor cannot hold another value object
of several values (record Order(Money Total, …)) — EF Core binds a constructor parameter to a column, never
to a complex type. The build refuses it (RASK103) rather than let the app fail when it
starts: give the outer type a private parameterless constructor and private setters, and it maps.
What is not a value object: a type EF Core maps as a column on its own (string, DateTime, Guid, an
enum, anything from System or Microsoft), a collection, an abstract or generic type, and an Entity<TId>.
A value object with several values is a complex type, not an owned entity, and the distinction is the point. An owned entity is a row
with hidden identity: tracked separately, nullable in ways a value has no business being, and quietly
producing a join. A complex type is part of the row, which is what a value object is, and it is why Money can
be held by two aggregates without either owning it.
Nesting works: a value object made of value objects is mapped all the way down. One EF Core constraint applies to the outer one: a complex type is materialised through its constructor, and EF cannot bind a nested complex type to a constructor parameter. So a value object that contains another value object needs a parameterless constructor and private setters, which is all EF Core needs:
// holds only scalars: a positional record is fine
public sealed record Money(decimal Amount, string Currency);
// contains a value object: a parameterless constructor and private setters
public sealed class Packaging
{
private Packaging() { }
public Packaging(Money cost, string material) => (Cost, Material) = (cost, material);
public Money Cost { get; private set; } = new(0m, "EUR");
public string Material { get; private set; } = "card";
}
A collection of value objects is not mapped automatically; configure it in the aggregate's own
Configure.
Splitting a total: Allocation.Split
A delivery shared among the vehicles that took fuel, a cost spread over categories: each share is rounded to what the
column keeps, and the shares must still add up to the total — rounding each one on its own loses or invents a cent.
Allocation.Split (namespace Rask.Values, in the Rask package) does it in one call:
IReadOnlyList<decimal> shares = Allocation.Split(100m, 3, step: 0.01m); // [33.34, 33.33, 33.33]
var byWeight = Allocation.Split(total, litres, step: 0.01m, remainder: Remainder.ToLargest);
- The sum is the total, exactly. Each share is its exact part rounded toward zero to a whole number of
steps; what that leaves over goes out a step at a time to the partsRemaindernames —ToFirst(the default: the first parts, in the order given),ToLast, orToLargest(the parts that lost most to the rounding, the earlier one first on a tie). No share is more than one step from its exact part. - Equal parts take a count (
Split(total, receivers.Count, step: 0.01m)); weighted parts take the weights. A weight of zero gets zero and none of the remainder; a negative weight, or none above zero, is refused. - A total off the step's grid (
10.005mby0.01m) keeps its last fraction on the part that takes the first step of the remainder ([5.005, 5.00]), so the sum still is the total. A negative total splits into negative shares. - Pure and deterministic — no database, no clock, no culture — so it belongs inside an aggregate's method, and the same arguments give the same shares on every host. Give the order a meaning (by moment, then number, then id) and the remainder lands on the same rows every time.
Strongly-typed ids
A typed id is one line:
public readonly partial record struct VehicleId(int Value);
public readonly partial record struct DriverId(Guid Value);
public readonly partial record struct PlateId(string Value);
public readonly partial record struct ShiftId(Guid Value);
public sealed class Vehicle : Aggregate<VehicleId> { }
public sealed class Shift : Aggregate<ShiftId>
{
public VehicleId Vehicle { get; private set; } // cannot be handed a DriverId: a compile error
}
What counts as one. A top-level, non-generic readonly partial record struct whose name ends in Id, with
exactly one positional parameter named Value of int, long, Guid or string. Leave out partial or
readonly, name it otherwise, or wrap another type, and it is an ordinary record struct that Rask still converts
to its value in the database (below) but does not complete.
What Rask completes it with (the Rask package's generator, so a domain library that references only Rask
gets it too):
| Member | Does |
|---|---|
VehicleId.Create() |
a new version-7 Guid, strictly increasing within the process (RFC 9562's counter in rand_a: two ids made in one millisecond still come out in order) — an id over a Guid only; the others come from the store or the caller |
VehicleId.Parse(s), VehicleId.TryParse(s, out id) |
the id s spells; IParsable<T> and ISpanParsable<T> too. An id over a string refuses "" (whitespace is kept: it may be a real key) |
id.ToString() |
the value alone — 42, 3e18ad13-… (lower case), ABC-123 — not VehicleId { Value = 42 } |
| JSON | the value alone: {"Vehicle":42}, and a Dictionary<VehicleId, …> is keyed by it; a number sent as text is read too |
| routing | [RouteParam] public VehicleId Id { get; set; } binds /vehicles/42, and Routes.VehiclePage(id) writes 42 back |
A member you write yourself — your own ToString, Parse or [JsonConverter] — is kept, and only the rest is
generated.
The JSON converter is a [JsonConverter] attribute, which JsonSerializer finds by reflection. A
JsonSerializerContext of your own (System.Text.Json's source generation) cannot see what another generator added, so
register it there: [JsonSourceGenerationOptions(Converters = [typeof(VehicleId.__JsonConverter)])] — or, simpler, keep
the reflection serializer for types that hold typed ids. Rask's own wire (commands, events, jobs) carries a typed id as
its bare value without either.
In the model. Use one as the aggregate's key and it is converted to its underlying value automatically. The
converter is registered once for the type, in ConfigureConventions, so every property of that type is
converted — the key, a foreign key on another entity, a nullable one — without any of them being named. An id the
generator cannot build a converter for is reported as RASK073 rather than left to fail
at model build. Ids that need no converter — Guid, int, long, string — are left alone.
On the read face a column of a type some entity is keyed by keeps that type, nullable as declared: an order line's
ProductId Product reads back as a ProductId, and a ProductId? ProductId as a ProductId? beside its inferred
Product navigation (what the face holds). A one-value type no entity is keyed by is
kept as itself too, like every value object — only it is no reference, so it gets no navigation.
Choosing the key: a typed id over a Guid
The default key is a typed id over a Guid, made by the entity itself:
public readonly partial record struct OrderId(Guid Value);
public sealed class Order : Aggregate<OrderId>, IHasTimestamps, IVersioned
{
public static Order Place(string reference)
{
var order = new Order { Id = OrderId.Create(), Reference = reference };
order.Raise(new OrderPlaced(order.Id)); // the row's id, from the first line
return order;
}
}
OrderId.Create() is a version-7 Guid (Uuid.Create()): time-ordered and strictly increasing — the 12 bits after
the millisecond count, where Guid.CreateVersion7() fills them at random, so two ids made in one millisecond still sort
in the order they were made (RASK148 points at a key set to Guid.CreateVersion7() or Guid.NewGuid()). The
primary-key index stays append-only as an identity's does, and unique without asking the database. That is what makes the id real before the
save: an event raised in the factory, a child pointing at its parent, a log line, a redirect to /orders/{id} all name
the row that will be written. rask new's first-entity example and a generated Create use it. ORDER BY Id and paging by it (Where(o => o.Id > last)) follow that time on SQL Server, PostgreSQL and SQLite alike — see
Guid keys sort by time on every database.
An integer identity is for a table the database must number — one an existing schema owns, or one whose number is the
business's (an invoice's, which Numbered keeps gap-free). Its Id is 0 until
the insert, and so is anything that read it first: an event raised in the factory with Id carries 0 for good, which
the build reports as RASK145 (an error under <RaskStrict>).
Who produces the key follows the value it holds:
- Over an
intor alongthe key is the store's identity, exactly as the integer would be:Vehicle.Create(…)inserts it and reads the number back, and a generatedCreatetakes noid. An application-numbered table saysb.Property(x => x.Id).ValueGeneratedNever()in itsConfigure, as for an integer key, and its generatedCreatetakes theidfirst. - Over a
Guidthe key is the application's:VehicleId.Create()in the factory, and a generatedCreatecallsVehicleId.Create()too. - Over a
stringthe caller names it: a generatedCreate(id, …)takes it first.
A Guid id in a text column is written lower case. Where the column holds text — every Guid on SQLite, or an
existing schema's text key — the id is written as ToString() prints it,
3e18ad13-d95e-4808-97bd-918b457c006b, rather than the provider's own spelling (SQLite's is upper case). A row an
older tool wrote in upper case still loads. Whether a Where by the id still finds it is the key column's comparison:
on SQL Server's usual _CI_ collations it does; a key is binary on SQLite
(BINARY) and PostgreSQL ("C"), and there it does not, so lower-case such a column once. A column that
stores a Guid natively (uniqueidentifier, uuid) is untouched.
Relationships: HasMany and BelongsTo
A relationship says which side of the border the other row is on. Inside the boundary are the aggregate's own parts, loaded and saved with it; across it is another aggregate, which this one only names. Rask has one word for each, and they read as the Rails and Laravel ones do:
| Rails | Laravel | Rask | The other row |
|---|---|---|---|
has_many :lines |
hasMany(Line::class) |
public HasMany<OrderLine> Lines { get; } = []; |
a child, inside the boundary: loaded, saved and deleted with the root (Children) |
belongs_to :vehicle |
belongsTo(Vehicle::class) |
public BelongsTo<Vehicle>? Vehicle { get; private set; } |
another aggregate, across it: the row stores its id, and nothing loads, tracks or saves it from here (below) |
fueling.vehicle = vehicle / vehicle_id = id |
->associate($vehicle) |
Vehicle = vehicle; / Vehicle = vehicleId; |
only the id is kept |
fueling.vehicle_id |
$fueling->vehicle_id |
fueling.Vehicle?.Id |
the id, typed, with no query |
Fueling.where(vehicle: v) |
Fueling::whereBelongsTo($v) |
Where(f => f.Vehicle == vehicleId) |
the column compared with the id |
fueling.vehicle.plate |
$fueling->vehicle->plate |
Fueling.Include(f => f.Vehicle) on the read face |
read, never loaded with the aggregate |
belongs_to :vehicle, optional: true |
->nullable() foreign key |
BelongsTo<Vehicle>? — required without the ? |
— |
has_one :address |
hasOne(Address::class) |
a value object (Address Address), its columns on the row |
a part with no identity of its own |
has_many :through, has_and_belongs_to_many |
belongsToMany(...) |
a link child — HasMany<DriverVehicle> on ONE side, its Sync(ids, …) (Children) |
the other side reads it on its read face |
The difference from Rails and Laravel is the border. There, fueling.vehicle hands back a live Vehicle you can change
and save along with the fueling; here an aggregate is a consistency boundary, so the other one is read — from its read
face, explicitly — and changed only by its own write. There is no lazy loading behind a property and no graph save across
aggregates. There is no HasOne either: a one-to-one part is a value object, and a child with an identity of its own
that an aggregate holds exactly one of has not come up in an app yet.
Another aggregate: BelongsTo
Declare the reference as a plain property with a private setter, on an entity — an aggregate or one of its children:
public sealed class Fueling : Aggregate<FuelingId>, IVersioned
{
public BelongsTo<Vehicle>? Vehicle { get; private set; } // optional: the fueling may name no vehicle
public BelongsTo<Driver> FilledBy { get; private set; } // required
public void Assign(VehicleId vehicle) => Vehicle = vehicle; // from its typed id
public void Assign(Vehicle vehicle) => Vehicle = vehicle; // from the aggregate: only its id is kept
public void Unassign() => Vehicle = null;
}
It holds the id and nothing else. Set it from the other aggregate's typed id (Vehicle = vehicleId, a VehicleId?
too) or from the aggregate itself (Vehicle = vehicle — its id only; a new one has its id from its factory already), clear
it with null, and read the id back typed, with no query: fueling.Vehicle?.Id is a VehicleId?, a required one's
fueling.FilledBy.Id a DriverId. Another aggregate's id does not convert (CS0029). An aggregate keyed by a plain
Guid, int or string has no type to carry the conversion, so its reference is made with
BelongsTo.Of<Quarry, Guid>(id) — or from the aggregate. Nothing is added to the entity: Rask registers each reference as
the assembly loads, and generates the typed Id and the typed id's conversion for every aggregate a reference in the same
project names.
It is one column, the reference's name plus Id — VehicleId, of the other aggregate's key type, nullable exactly
when the reference is — the column a hand-written VehicleId had. EF Core reads and writes it through the entity's own
indexer, so the reference is the one place the id is held: a load fills it, a save writes it, and a Reload() or a
CurrentValues.SetValues(…) puts the row's id back into it. Configure the column through the reference, never by a
string: b.Property(f => f.Vehicle).HasColumnName("vehicleId"), b.HasIndex(f => new { f.Pump, f.Vehicle }) — Rask moves
both onto the column. ApplyRaskConventions() (which RaskDbContext calls) maps it; a context that never calls it is
refused with that line rather than EF Core's "could not be mapped".
A query of the aggregate compares it with an id, and the database compares the column:
var fuelings = await db.Set<Fueling>().Where(f => f.Vehicle == vehicleId).ToListAsync(); // WHERE vehicle_id = @vehicleId
var loose = await db.Set<Fueling>().Where(f => f.Vehicle == null).ToListAsync(); // WHERE vehicle_id IS NULL
Compared with another reference instead (f.Vehicle == other.Vehicle), the other side reaches the query as an object no
database holds: RASK135 says so — compare with other.Vehicle?.Id, read before the query.
Reading the other aggregate is the read face's, on purpose and out loud — the reference itself never queries:
// on a query, the read face's navigation of the same name
var rows = await Fueling.Include(f => f.Vehicle).ThenInclude(v => v.Owner);
var plates = await Fueling.Where(f => f.Vehicle!.Plate.StartsWith("AB")).Select(f => f.Vehicle!.Plate);
var id = fueling.Vehicle?.Id; // one row, by the id it holds
VehicleRead? vehicle = await Vehicle.Where(v => v.Id == id).FirstOrDefault();
ThenInclude continues an Include on any read face — a reference, a child list
(Order.Include(o => o.Lines).ThenInclude(l => l.Product)) or the rows that point here — and, as in EF Core, only right
after the Include it continues. On the target the reference works backwards like any inferred one:
VehicleRead.Fuelings, the fuelings whose VehicleId is the vehicle's (the rows that point
here).
Nothing about it is part of this aggregate's load or save. Fueling.Find(id) loads the fueling and its children, not
the vehicle; a save writes the VehicleId column and nothing of the vehicle's. Asking EF Core to load one anyway —
db.Fuelings.Include(f => f.Vehicle) on the write context, or a ThenInclude onto one — is
RASK195, an error: EF Core maps the id and no navigation, which is the border.
It is a foreign key that never cascades. The relationship is mapped as HasOne<Vehicle>().WithMany() over the
column, with OnDelete(DeleteBehavior.NoAction) — a vehicle a fueling still names cannot be deleted, the database says
so, and a context holding both never nulls the fueling's id (what deleting a referenced row
says). There is nothing to write for that; to say another OnDelete, or the
sentence a refused delete fails with, name the relationship through the reference:
public static void Configure(EntityTypeBuilder<Fueling> b)
{
b.Reference(f => f.Vehicle).OnDelete(DeleteBehavior.SetNull);
b.Reference(f => f.FilledBy).OnDelete(DeleteBehavior.NoAction, "The driver has fuelings and cannot be deleted.");
}
Moving to it is no migration. A hand-written id — public VehicleId? VehicleId { get; private set; }, with or without
a Vehicle navigation beside it, with or without the HasOne<Vehicle>().WithMany().HasForeignKey(…) that configured it —
is the same column, the same index and the same constraint, so EF Core's migration differ finds nothing between them on
SQLite, SQL Server and PostgreSQL. Two things do move, and say so: a required reference whose relationship was left to
EF Core's default deletes in cascade, and becomes NoAction (say Reference(…).OnDelete(DeleteBehavior.Cascade) to keep
it); an id that had no relationship at all gains its foreign key and index. The read face keeps its Vehicle navigation
and its VehicleId column as they were. RASK196 suggests the move — the aggregate an id names is
found as the read face finds it: a typed id by its type, a configured relationship by its HasOne<T>(), any other id by
its name — and its quick-fix makes it, Fix all for a whole app in one pass: the property becomes the reference,
VehicleId = id becomes Vehicle = id, a read x.Vehicle?.Id, a comparison x.Vehicle == id (in a query too), an index
or a column name the reference's, and the HasOne…HasForeignKey line goes —
or becomes Reference(x => x.Vehicle) where it said more than Rask does by itself (an OnDelete other than NoAction).
What it cannot be, each RASK194, an error: a reference that is partial (the retired
form, with a quick-fix to { get; private set; }) or has neither a setter nor a backing field ({ get; } set by a constructor is fine), on a type that is no entity, is generic or is
nested where generated code cannot see it; to something that is not an aggregate (a child is reached through its root, or
by its id), to the tenant (that is IBelongsTo<Tenant>), or — from a child — to the
root that holds it, which reaches it already; and a column name the entity already uses for a member of its own.
On a form it is the id it holds. An entry takes a BelongsTo<Vehicle>? Vehicle as the id —
VehicleId? vehicle in a written Create or step, and in a generated one — so its
field is the vehicle's key type, under the reference's name, and a picker binds it with nothing in between:
Form.For(Fueling.Update, id)[f => [
Ui.Select.Bind(() => f.Vehicle).Choices(Vehicle.Choices(v => v.Plate)),
Ui.Button.Submit["Save"],
]]
An edit form reads the id off the stored reference, and the save writes back the reference that id makes — never an
object. A required reference (BelongsTo<Driver> FilledBy) is a required field with the same message as any other, and a
create form starts with nothing picked; an optional one left empty clears the reference. A query string parses it
through the key's own IParsable, and a check the store asks as the field is left — a unique rule over the column, or a
tenant's reference — is told under Vehicle, not VehicleId.
Children
An aggregate holds its parts. Declare them as Entity<TId> and hold them in one HasMany<TChild>, started with the
empty collection expression = [] — nothing else is configured, and no EF HasMany(…) call, no foreign key and no key
generation is written anywhere:
public sealed class Order : Aggregate<Guid>, IHasTimestamps, IVersioned, IUpdatable, IDeletable
{
public string Reference { get; private set; } = "";
public HasMany<OrderLine> Lines { get; } = [];
public static Order Place(string reference) =>
new() { Id = Uuid.Create(), Reference = reference };
public OrderLine Add(string product, int quantity) // the aggregate guards its own invariants
{
var line = OrderLine.For(product, quantity);
Lines.Add(line);
return line;
}
}
public sealed class OrderLine : Entity<Guid>
{
public string Product { get; private set; } = "";
public int Quantity { get; private set; }
public void SetQuantity(int quantity) => Quantity = quantity;
internal static OrderLine For(string product, int quantity) =>
new() { Id = Uuid.Create(), Product = product, Quantity = quantity };
}
{ get; } = []; is the one way to write it: plain C#, no generator and no partial. = new() and
= new HasMany<OrderLine>() say the same another way — the same property over the same backing field, so EF Core maps
them alike and the move is no migration — and are RASK201's (a suggestion, an error under
<RaskStrict>), whose quick-fix — Fix all does a document, a project or the solution — writes = []. Children the
aggregate always starts with go in the same place: { get; } = [Part.Spare()] is the aggregate's own, while one
that starts the property from another type (new Order { Lines = [line] } through an init) is
RASK180's.
Only the aggregate changes them. Everyone reads Lines — it is an IReadOnlyList<OrderLine> — and only Order
changes it: Add (one child, or several),
Remove, RemoveAll(match), Clear() and Sync called from any other type, or on the children held in a local, or
the collection cast to ICollection<OrderLine> there, or the property started from [line, …] there, are
RASK180, an error. It is also the
collection EF Core maps, through the property's own backing field: a child added is inserted, one changed is updated,
one let go is deleted, all in the aggregate's save, and Find loads them with the root.
Moving from the hand-written pair — private readonly List<OrderLine> _lines = []; and
public IReadOnlyList<OrderLine> Lines => _lines; — is no migration: the navigation keeps its name and the child
its foreign key (OrderId), and the schema EF Core creates is the same to the byte. RASK193
suggests the move (an error under <RaskStrict>) and its quick-fix makes it — HasMany<OrderLine> Lines { get; } = [];,
_lines.Add(line) becoming
Lines.Add(line). A read-only auto-property refilled whole — IReadOnlyList<OrderLine> Lines { get; private set; } = [];
with Lines = [.. Lines, line] — still works too: Rask hands EF Core a collection it can add to as it loads or saves.
The order is kept only when it is asked for. A store returns rows in no order of its own, so the children load in
whatever order it reads them. Where the order is the data — the lines of a document, the items of a checklist — say so
in the aggregate's Configure:
public static void Configure(EntityTypeBuilder<Supply> b) => b.InOrder(s => s.Parts);
Each part's place is then stored in a Position column Rask adds to the child's table (Columns.Position, a shadow
property written on every save — so declaring it on children already stored is a migration), and the parts load back in
the order the aggregate last gave them. A child that declares a Position of its own keeps it. Nor is the key an order: a
version-7 id is time-ordered only to the millisecond and random below it, so two children made in one Sync sort either
way by it. A form's row list (Form.For(Supply.Update, id)) reads the children in the order they loaded, so a list
people edit by place — and expect back as they left it — is one to declare InOrder.
Children made from a form's rows: Sync. When the children are whatever a list of rows says — a delivery's parts,
a driver's chips — let Sync do the add/change/remove loop:
public sealed record SupplyPartSpec(SupplyPartId? Id, TankId Tank, decimal Quantity); // a row of the form
public sealed class Supply : Aggregate<SupplyId>
{
public HasMany<SupplyPart> Parts { get; } = [];
public void Change(IReadOnlyList<SupplyPartSpec> parts)
{
var sync = Parts.Sync(parts, s => s.Id,
add: SupplyPart.For, // a spec whose key is null, or names no part of this supply
update: (p, s) => p.Hold(s), // a spec whose key is a part's Id
remove: p => p.Release()); // optional: a part no spec names, as it is let go
if (sync.Removed.Count > 0) Raise(new PartsReleased(sync.Removed));
}
}
After it, Parts is in the specs' order — the order a form posted them, so a part's rule fails under
Parts[1].Quantity as for any child. Sync returns what it did: Added, Changed (a part whose update moved one of
its public properties — one its row left as it was is not there), Removed, and Touched (added or changed), which is
what a rule over old rows asks so a row stored before the rule was tightened is let be. The key is the child's own Id
type — a SupplyPartId?, not its Guid. A key given twice throws: two rows naming one part, or a key of another
type, are refused with an ArgumentException before any part is touched — de-duplicate the rows first if they can
repeat (parts.DistinctBy(p => p.Id)), deliberately, since which of two rows wins is the caller's decision. The
form over such a method is Form.For(Supply.Update, id) — a row per part, refused under its place
(a form over an operation).
Children matched by something other than their Id — a delivery note's fuellings by their transaction — take a key
of their own on both sides, with the same refusal of a key named twice:
Fuellings.Sync(fuellings, f => f.TransactionId, f => f.TransactionId,
add: DeliveryNoteTransaction.For, update: (f, s) => f.Use(s.Quantity));
A link — children that each name one row of another aggregate and hold nothing else, a driver's vehicles — is synced from the other side's ids alone: a child whose id is among them stays, an id no child holds adds one, the rest are let go, and an id given twice throws.
public SyncResult<DriverVehicle> Drive(IReadOnlyList<VehicleId> vehicles) =>
Vehicles.Sync(vehicles, v => v.VehicleId, add: DriverVehicle.For);
Loading one root loads it whole. Every write that starts from an id brings the children with it, and so
does db.Orders.FindAsync(id). On the read face the children are an ordinary navigation, so you ask for them
when you want them — listing a thousand orders should not drag in every line each of them holds:
await Order.Update(id, o => o.Add("anvil", 1)); // loaded whole, changed, saved
var open = await Order.Where(o => o.Reference.StartsWith("2026")); // Lines EMPTY
var withLines = await Order.Query((q, ct) => q.Include(o => o.Lines).ToListAsync(ct));
// …and a child is queryable on its own, because the read side has no borders:
var heavy = await OrderLine.Where(l => l.Quantity > 10 && l.Order.Reference.StartsWith("2026"));
A change to any part is a change to the whole. A line's quantity moving stamps the order's UpdatedAt and
bumps its Version (it says IHasTimestamps and IVersioned), so the version a caller read stops being current — which is what makes the aggregate, and
not the row, the unit of concurrency:
await Order.Update(id, o => o.Lines.First().SetQuantity(5));
// UPDATE OrderLine SET Quantity = 5 …
// UPDATE Order SET Version = Version + 1, UpdatedAt = @now WHERE Id = @id AND Version = @read
A generated Update takes them as rows, and syncs them. An IUpdatable Order that writes no Update of its own
gets one (a generated Create and Update) taking IEnumerable<OrderLineRow>? lines,
each row carrying the child's Id so the save knows which stored line it is; its form is Form.For(Order.Update, id),
a row per line (f.Lines[i].Quantity):
await Order.Update(order.Id, order.Version, "2026-001", lines: [
new OrderLineRow("anvil", 9, Id: anvilId), // edits that line
new OrderLineRow("rope", 2), // no Id: a new line
]); // the "spring" line is in no row: DELETED
What the posted list holds is what the aggregate holds afterwards. A row with no
Idis added, a row whoseIdmatches a stored child updates it, and a stored child whose id is in none of the posted rows is removed — so a form that renders only some of the lines deletes the rest, and an empty list deletes them all. Bind the whole collection, or apply the change through a domain method (Order.Update(id, o => o.Add(…))) instead of a partial list.
An Id that matches nothing in this aggregate is never followed: it lands as a new child with an id of its
own. A posted id therefore cannot reach — or delete — another aggregate's line.
A child cannot outlive its parent. Rask makes the relationship required and its delete a cascade, so taking a
line out of the collection deletes the row. Left to EF Core's own convention the foreign key would be nullable,
and severing a child would set that key to NULL and leave the row in the table — invisible through the
navigation, unreachable through the aggregate, and impossible to delete through it either.
Deleting the aggregate follows the same rule: Order.Delete(id) removes the order and its lines with it.
An order that says ISoftDeletes instead of IDeletable is different, and deliberately
so: DeletedAt is stamped rather than the row removed, so nothing cascades and the lines are still there if the
order comes back.
The child gets a table, a row on its parent's generated writes, and a read face of its own —
OrderLine.Where(…) — because the read side has no borders. It gets no writes of its own: there is no
OrderLine.Create, no version and no soft delete, because it is not a thing you save on its own. A collection of
another aggregate is not a child at all (RASK087); a collection that is no HasMany leaves the aggregate with no generated Create or
Update.
The field behind a read-only view can be named anything — Notes => _items.AsReadOnly() — and can live on an
abstract base, generic or not: the collection is loaded into and saved from that field, not the view.
A child is written only through its aggregate. A save that adds, changes or removes a child whose root the
same context does not hold — a line found through db.OrderLines and edited, a new OrderLine attached on its
own, a BulkInsert of lines — is refused with an InvalidOperationException naming the child and its root.
Tenant.Across() does not lift it: it is about the aggregate's shape, not whose rows are visible. Load the
order, change it, save the order:
await Order.Update(id, o => o.Lines.First().SetQuantity(5)); // ✓ through the aggregate
var line = await db.OrderLines.FirstAsync(ct);
line.SetQuantity(5);
await db.SaveChangesAsync(ct); // ✗ 'OrderLine' was changed on its own … load its 'Order'
Timestamps are the aggregate's, like its tenant. A child has no CreatedAt or UpdatedAt — not in its
table, not on OrderLineRead, never stamped — and the root's UpdatedAt moves whenever any of its children is
added, changed or removed, so it means "anything in this order changed". A child whose table does carry them
says the trait, and keeps them — the timestamps and ISoftDeletes are the only traits an Entity says:
public sealed class OrderLine : Entity<Guid>, IHasTimestamps // this child table has CreatedAt and UpdatedAt
{
}
A key of several columns
A child that is the meeting of two aggregates (which transactions fuelled which delivery note) is keyed by the pair,
not by an Id of its own. Declare the key as a tuple of the types it joins, and make the class partial:
public sealed class DeliveryNote : Aggregate<int>, IBelongsTo<Tenant>
{
private readonly List<DeliveryNoteTransaction> _fuellings = [];
public IReadOnlyList<DeliveryNoteTransaction> Fuellings => _fuellings;
public void Fill(IEnumerable<(int TransactionId, decimal Quantity)> rows)
{
_fuellings.Clear();
_fuellings.AddRange(rows.Select(r => DeliveryNoteTransaction.For(r.TransactionId, r.Quantity)));
}
}
public sealed partial class DeliveryNoteTransaction : Entity<(DeliveryNote, Transaction)>
{
public decimal Quantity { get; private set; }
internal static DeliveryNoteTransaction For(int transactionId, decimal quantity) =>
new() { TransactionId = transactionId, Quantity = quantity };
}
Rask generates the rest. Each aggregate in the tuple becomes a {Aggregate}Id of that aggregate's own key
type, so it is never written twice. Id becomes the key's values together:
// generated
public int DeliveryNoteId { get; private set; }
public int TransactionId { get; private set; }
public new (int DeliveryNoteId, int TransactionId) Id => (DeliveryNoteId, TransactionId);
The table's primary key is (DeliveryNoteId, TransactionId), in the order the tuple names them, and nothing
generates either value. A part that is a plain value is named, and the entity declares it:
Entity<(Order, int LineNo)> with public int LineNo { get; private set; }. The same key reaches a context you
wired yourself, through ApplyRaskConventions.
It reads like any child. The read face lists the key's parts where Id would be. Each part infers its navigation
by the usual {X}Id rule. The tenant comes through the aggregate that holds it, so the row needs no TenantId
of its own:
var fuellings = await DeliveryNoteTransaction.Where(t => noteIds.Contains(t.DeliveryNoteId))
.Select(t => new { t.DeliveryNoteId, t.TransactionId, t.Quantity, t.Transaction.ProductId });
var note = await DeliveryNote.Include(n => n.Fuellings).First(n => n.Id == id);
It is written through its aggregate, like any child. The entity makes itself in a factory of its own, setting
the parts it knows — the generated ones have private setters, so its own type can set them — and Rask fills the
part that names the holding aggregate when the save attaches it. Replacing the whole collection, as Fill does,
is the usual shape, and the save matches the new rows to the stored ones by key:
await DeliveryNote.Update(id, n => n.Fill(rows));
// stored (10, 12.5) (11, 3.25) (13, 2) ← rows (10, 12.5) (11, 4) (12, 1)
// UPDATE DeliveryNoteTransactions SET Quantity = @p0 WHERE DeliveryNoteId = @p1 AND TransactionId = @p2 (11)
// INSERT INTO DeliveryNoteTransactions (DeliveryNoteId, TransactionId, Quantity) VALUES (…) (12)
// DELETE FROM DeliveryNoteTransactions WHERE DeliveryNoteId = @p0 AND TransactionId = @p1 (13)
// nothing for (10)
var note = DeliveryNote.Issue("A-1", rows); // a factory of the note's own, which calls Fill
await note.Save(); // the note, then its rows under the note's new key
The same holds for Find + Save() and for a shared context (db:): every row the aggregate holds afterwards is in
the table, and nothing else is. A row changed or added without its aggregate is refused, as for any child.
A grandchild names the child that holds it. A column of a report, keyed by the report and its own number, holds totals keyed by the column and theirs. The column's whole key becomes the grandchild's, one generated property per part, named as EF Core names a foreign key to it:
public sealed partial class ReportColumn : Entity<(Report, int ColumnId)>
{
private readonly List<ReportGroupTotal> _totals = [];
public int ColumnId { get; private set; }
public IReadOnlyList<ReportGroupTotal> Totals => _totals;
}
public sealed partial class ReportGroupTotal : Entity<(ReportColumn, int TotalColumnId)>
{
public int TotalColumnId { get; private set; }
}
// generated: ReportColumnReportId, ReportColumnColumnId, and
// public new (int ReportColumnReportId, int ReportColumnColumnId, int TotalColumnId) Id
A column that is replaced takes the new instance's totals with it, and they are matched by key the same way.
A class that is not partial, a part with no name or a named aggregate or entity part, a name that is already
taken, and a key of several columns on an aggregate root are RASK106.
Link tables and child rows on the form
Both shapes reach a form through an entry, and are saved in the aggregate's one save. Tables an existing app made — a company and the activities it does, a report and its columns:
public sealed class Company : Aggregate<int>, IUpdatable, IBelongsTo<Tenant> // Tenant : Aggregate<int>, ITenant
{
public string Name { get; private set; } = "";
public HasMany<CompanyActivity> Activities { get; } = [];
}
public sealed partial class CompanyActivity : Entity<(Company, Teaor)> { } // CompanyTeaors(CompanyId, TeaorId)
A link — the holder's part and one other, and nothing else — is a list of ids, synced as a set: a link is
added for an id it does not hold yet, removed for one no longer listed, never updated, and the same set in another
order writes nothing. Company writes no Create or Update, so the generated ones
take it, named after the collection, made singular, plus Ids (Activities → activityIds, Statuses →
statusIds, People → personIds); the singular follows Rails' rules — ies → y, es dropped where it was added
(after x/ch/sh/ss/zz, and Statuses, Buses, Aliases), a final s, and a short list of irregular plurals — and a
name no rule makes singular keeps the collection's own (staffIds). On the form it is one field holding the ids,
filled from the links the aggregate holds:
Form.For(Company.Update, id)[f => [
Ui.Input.Bind(() => f.Name).Label("Name"),
Ui.Pillbox.Bind(() => f.ActivityIds).Choices(Teaor.Choices(t => t.Name)).Label("Activities"),
Ui.Button.Submit["Save"],
]]
await Company.Update(id, version, "Acme", activityIds: [teaorA.Id, teaorB.Id]); // INSERT the new link, DELETE the dropped one
Laravel's $company->teaors()->sync($ids) and Rails' company.teaor_ids = ids.
A row with fields of its own is a list of rows — a spec of the parts of the key the holder does not give
(ColumnId here, TransactionId for Entity<(DeliveryNote, Transaction)>) and the row's own fields. A child keyed
by the caller is the aggregate's to write (a generated Update does not guess at
it), as a step that syncs the rows by key, as a refill is above:
public sealed class Report : Aggregate<int>, IVersioned
{
public HasMany<ReportLine> Lines { get; } = [];
public void Arrange(IReadOnlyList<ReportLineSpec> lines) =>
_ = Lines.Sync(lines, l => l.ColumnId, s => s.ColumnId, add: ReportLine.For, update: (l, s) => l.Set(s));
}
public sealed record ReportLineSpec(int ColumnId, int Order, bool Sum);
public sealed partial class ReportLine : Entity<(Report, int ColumnId)>
{
public int ColumnId { get; private set; }
public int Order { get; private set; }
public bool Sum { get; private set; }
internal static ReportLine For(ReportLineSpec s) => new() { ColumnId = s.ColumnId, Order = s.Order, Sum = s.Sum };
internal void Set(ReportLineSpec s) => (Order, Sum) = (s.Order, s.Sum);
}
Form.For(Report.Arrange, id) holds f.Lines, a row per stored line read off it by the spec's member names; the
save updates a changed row, inserts a new key and deletes a dropped one. The holder's part is never on the form: the
save fills it. Inside Db.Transaction either entry joins the transaction with everything else, so several aggregates
saved together are one transaction. A per-tenant holder keeps its rows to its tenant through itself — the rows carry
no TenantId.
What a form is told. A row member left empty that may not be is required under its own field
(Lines[0].ColumnId). A key given twice is refused by Sync before any row is touched. An id the database refuses —
no such activity, the foreign key the table declares — is a field error saying ValidationNotFound, and the whole
save, every aggregate in it, is rolled back, in the reader's language — the kit carries Hungarian — and an app's own
catalog overrides it (Localization).
What a form cannot carry is a row that holds rows of its own (a ReportColumn holding Totals): no Form.For is
made for such an entry (RASK188); fill those through a method of the aggregate.
Collections of values
A collection whose elements are values rather than entities is one column, not a table. Declare it the same way as a child — a private field and a read-only view — and nothing else is configured:
public sealed class Trip : Aggregate<Guid>
{
private readonly List<string> _tags = [];
private readonly List<Stop> _stops = [];
public IReadOnlyList<string> Tags => _tags; // one column of plain values
public IReadOnlyList<Stop> Stops => _stops; // one JSON column of value objects
public void Tag(string tag) => _tags.Add(tag);
public void StopAt(string city, int day) => _stops.Add(new Stop(city, day));
}
public sealed record Stop(string City, int Day);
Tags becomes a primitive collection and Stops a JSON column. Both appear on
the read face, and both are queryable in SQL:
await Trip.Where(t => t.Tags.Contains("urgent"));
await Trip.Where(t => t.Stops.Any(s => s.City == "Vienna" && s.Day >= 2));
Values are replaced wholesale, not reconciled. A child has an id, so a form post updates the rows it names and deletes the rest. A value has no id, so there is nothing to match against: what the form posts is what the aggregate holds afterwards, and an empty list clears the collection.
The column is NULL only where the model says it may be. Tags and Stops above are NOT NULL, and an empty
collection is stored as [], never as NULL. A nullable one, List<Stop>? Detours { get; private set; }, is a NULL
column. This works the same way as Laravel's $table->json('stops') and Rails' t.json :stops, null: false. An
adopted Stops nvarchar(max) NOT NULL column is mapped as it is, with no migration.
The column is the database's own text of any length: nvarchar(max) on SQL Server at every compatibility level
(EF Core alone would make it SQL Server 2025's json at 170, and change the model — and so the migrations — with the
level the server reports), TEXT on SQLite and jsonb on PostgreSQL. A plain value collection (List<string>) is
kept the same way. No app names the type; a SetContainerColumnType(…) or HasColumnType(…) of its own still wins.
A JSON column is an EF Core complex collection, which EF Core writes through a list, so the property needs a
List<T> behind it. A get-only IReadOnlyList<T> auto-property keeps a NULL column, whatever its nullability:
public IReadOnlyList<Stop> Stops { get; private set; } = new List<Stop>(); // NULL column: no list behind it
private readonly List<Stop> _stops = [];
public IReadOnlyList<Stop> Stops => _stops; // NOT NULL: the field is the list
public List<Stop> Stops { get; private set; } = []; // NOT NULL: the property is the list
The first shape is mapped the old way, as an owned collection, and EF Core makes an owned collection's column NULL and
refuses IsRequired() on it.
Moving an existing app onto NOT NULL is one migration, with no edit. Every value-object collection used to be a
NULL column, so the next rask db add writes an AlterColumn to NOT NULL for each non-nullable one, with
defaultValue: "[]". SQLite, SQL Server and PostgreSQL fill every NULL row with [] before the column turns
NOT NULL, and an AddColumn of a new collection fills the rows already there the same way. EF Core on its own would
write "{}", an object that no collection can read back, so a context writes its migrations through Rask's differ
when it is on UseRaskSqlite, UseRaskPostgres or UseRaskSqlServer, or is a RaskApp's. A context on plain
UseSqlite, UseNpgsql or UseSqlServer gets EF Core's "{}": switch it to the Rask call. A JSON column that holds
one value object keeps "{}".
Choose a child entity instead when the elements need identity — to be referenced, updated one at a time, or indexed. That is the real trade-off, and the deciding factor is usually the index:
| SQLite | PostgreSQL | SQL Server | |
|---|---|---|---|
| plain values | json_each |
native text[] |
OPENJSON |
| value objects | json_each |
jsonb |
OPENJSON |
| index over every element | none | GIN | — |
PostgreSQL can index straight into both. SQLite needs no extension for JSON (json_extract is core since
3.38), and it can index a fixed path through a generated column — but it has no equivalent of GIN, so a
filter over any element of the collection is a scan. If that filter is hot on SQLite, make the elements
Entity<TId> children and index the column.
byte[] is never a collection of bytes: it stays one BLOB column. Anything Rask has no column for — a
Dictionary, a collection of some framework type — is left alone for the entity's own Configure to map, and
so is any collection that Configure already mapped.
A converter on the element is read back on the read face too — an enum list stored by name, or values the app stores its own way:
builder.PrimitiveCollection(s => s.Handling).ElementType().HasConversion<string>(); // ["Fragile","Cold"]
await Skid.Where(s => s.Handling.Contains(SkidHandling.Cold)); // the enum, not its name
A list that is a value: ValueList<T>
A List<T> is compared by reference, so a value object that holds one is never equal to another holding the same
elements, and anything holding the list can change it under the value object's feet. ValueList<T> (namespace
Rask.Values) is the list that is a value: equal by its elements in order, and never changed once made — a
collection expression makes one, and a new list replaces it:
public sealed class Tenant : Aggregate<TenantId>, IVersioned
{
public ValueList<CategoryCode> Codes { get; private set; } = []; // a JSON column, as IReadOnlyList<T> is
public void Classify(params CategoryCode[] codes) => Codes = [.. codes];
}
On an aggregate or an entity it takes the same column an IReadOnlyList<T> does — a primitive collection of plain
values, a JSON column of value objects, NOT NULL and [] when empty — and is queried the same way
(Tenant.Where(t => t.Codes.Contains(code))). It implements IList<T> only because that is what EF Core reads a
JSON collection into: once anything has read it, a change through that interface throws NotSupportedException.
One value object kept whole as JSON: b.Json(…)
A value object of several members is a complex type, one column per member. A value object that holds a list —
a partner's settings, a set of pairings — has no columns to spread over, so it is kept whole in one JSON column,
named in the entity's Configure:
public sealed record LocalWell
{
private LocalWell() { } // EF Core builds a holder of a list
public LocalWell(LocalWellProvider provider, Secret<ApiKey>? key, ValueList<Pair> tanks) => // through its members
(Provider, Key, Tanks) = (provider, key, tanks);
public LocalWellProvider Provider { get; private init; }
public Secret<ApiKey>? Key { get; private init; }
public ValueList<Pair> Tanks { get; private init; } = [];
}
public sealed partial class Tenant
{
public LocalWell? LocalWell { get; private set; }
static void Configure(EntityTypeBuilder<Tenant> b) => b.Json(t => t.LocalWell, column: "LocalSettings");
}
column: names a column an adopted table already has; without it the column is named after the property. A
nullable member is a NULL column while it holds nothing. It is EF Core's own JSON mapping, so the column is TEXT
on SQLite, nvarchar(max) (or json) on SQL Server and jsonb on PostgreSQL, a filter on what is inside runs in
the database on all three (Tenant.Where(t => t.LocalWell!.Provider == provider), ….Tanks.Any(p => p.DbId == id)),
and the conformance suite proves it on each (JsonValueParityTests). b.Json(…) on a collection of value objects
renames its JSON column. The read face holds a value object kept as JSON as itself, on the same column.
EF Core builds a value object that holds another, or a list, through its members rather than its constructor — so
such a holder has a private parameterless constructor and private init members, as above.
Secrets: Secret<T>
An API key a partner issued, a token the app must send on: a value the app stores and uses but never shows.
Declare it Secret<T> — over a string, or over a value object that holds one text (its rules checked as it is
made):
public sealed partial record ApiKey(string Value) : Text(Value, MaxLength: 200);
public sealed partial class Partner
{
public Secret<ApiKey>? Key { get; private set; }
public void Connect(Change<ApiKey> key) => Key = Secret.Applied(key, Key); // empty field: keep; typed: replace
}
- Stored as ciphertext. The column — and a
Secret<T>inside a JSON column, asLocalWell.Keyabove — holds the value encrypted throughISecrets, which Rask.Server backs with the host's ASP.NET Core Data Protection key ring (the ring a Rask deploy persists to its volume, under a purpose of its own). A dump, a backup or a logged SQL parameter shows nothing usable. A row stored before a rule was tightened still loads. Keep the key ring as long as the data: a ciphertext is only readable with the keys that wrote it. - Never shown.
ToString()and the debugger say••••, and it has no public member, so a serializer writes{}. The read face leaves it out, and an aggregate holding one gets no generatedCreateorUpdate— no form has a field for it unless an operation takes one: it is never prefilled into a form and never sent to a browser. - Set through an operation that takes the plain value object.
Change<ApiKey>gives the form an empty field that keeps the stored key unless something is typed, andSecret.Appliedwraps what was typed. ReadKey.Reveal()in the one place the key is used — the request to the partner. - A host wired by hand registers its own
ISecrets; a test setsSecretKeeping.Defaultto one. ASecret<T>of aPasswordvalue object is not RASK175: it is kept as ciphertext, which is what a password the app must send on asks for. A sign-in password is still hashed, never kept.
A file the row holds: Attachment
A file that belongs to a row — a registration scan, an invoice's PDF — is a value of the aggregate too. It comes in as
a file value object, declared like a Text with its rules as the base's arguments, and the aggregate keeps it as an
Attachment:
public sealed partial record InvoiceScan(Upload File) : FileValue(File, MaxSize: 10.Megabytes, Types: [".pdf", ".jpg", ".jpeg"]);
public sealed partial class Invoice : Aggregate<InvoiceId>, IVersioned
{
public Attachment? Scan { get; private set; }
public void Attach(InvoiceScan scan)
{
if (Scan is not null) Refuse("Már van feltöltve számla.");
Scan = Attachment.Of(scan); // stored through Rask.Storage when the operation saves
}
public void Detach() => Scan = null; // the file goes once the save commits
}
// The page: the operation's form holds the picked file, and its picker is told the rules.
Ui.Field.Bind(() => f.Scan).Label("Számla") // or Ui.FilePicker.Bind(() => f.Scan)
- Checked as it is made, synchronously.
InvoiceScan.Create(upload, field)refuses a missing or empty file, one larger thanMaxSize, one whose extensionTypesdoes not name, and one whose bytes are not of the type its name says — a.pdfmust start%PDF-, a.jpgFF D8 FF, a.png,.gif,.webp,.zip,.docx/.xlsx/.pptx,.doc/.xlstheir own signatures. A type with no known signature (.csv,.txt,.xml) is checked by its name alone. Every check reads theUploadalready in hand — its bytes are in memory — so nothing awaits.Message:puts every refusal but a missing file in the app's own words; otherwise Rask's catalog says them (in Hungarian too). - In the browser, before it is uploaded. A form over
Invoice.Attachholds the file as anUpload?field and draws aUi.FilePickertold the value object's rules: its input'sacceptis.pdf,.jpg,.jpeg, and a file too large or of another type is refused from its name and size before a byte is read, with the value object's own message under the field. The bytes' signature is asked when the form makes the value object, on submit. - Configured per value object.
Rask:Uploads:InvoiceScan:MaxSize(bytes) andRask:Uploads:InvoiceScan:Types(a list, or".pdf,.jpg") win over what is declared, which stays the default — read once as the host starts, so an install raises its limit without a build. That is the whole of an app's upload settings: no options class of its own. - Stored with the row.
Attachment.Of(scan)is pending: the bytes are written by the operation's own save, inside its transaction, and a file the save replaces is let go after the commit. The store sniffs the type and checks its ownMaxFileSizeagain. File storage has the whole of it.
Operations: what the aggregate does
An aggregate is not updated: it is placed, paid, shipped or cancelled, and each of those is a public method on it
that keeps its own rules. That method is the whole of a write — there is no handler to put around it and no service
to call it from. Rask gives each one a static entry that loads the aggregate, runs the method and saves it in one
transaction, a dry run a form asks while it is filled in, and a May… that says whether the signed-in user may run
it.
CRUD names: Create, Update, Delete
An aggregate's writes carry the names Rails and Laravel give them. The rule: an entry is ONE step — the load, the
step and the save in one call, called by the type's name — and several steps in one save are the aggregate flow:
Find (or New), the steps on the aggregate in hand, then Save().
| What | Rails | Laravel | Rask |
|---|---|---|---|
| make and save | Supply.create(attrs) |
Supply::create($attrs) |
var s = await Supply.Create(…) — the saved aggregate, its Id and Version set |
| make, save later | Supply.new(attrs) |
new Supply($attrs) |
var s = Supply.New(…) — in memory; await s.Save() inserts it |
| read | s = Supply.find(id) |
$s = Supply::find($id) |
var s = await Supply.Find(id, version) |
| edit, one call | s.update(attrs) |
$s->update($attrs) |
await Supply.Update(id, version, …) or await Supply.Update(s, …) |
| a step, one call | s.close! |
$s->close() |
await Supply.Close(id, version) or await Supply.Close(s) |
| delete, one call | s.destroy |
$s->delete() |
await Supply.Delete(id, version) or await Supply.Delete(s) |
| several steps, one save | s.assign_attributes(…); s.close; s.save |
$s->fill(…); $s->close(); $s->save() |
s.Update(…); s.Close(); await s.Save(); |
- Every step entry also takes the aggregate in place of
(id, version):Supply.Close(supply)isSupply.Close(supply.Id, supply.Version)— the stored aggregate is loaded at the version the one in hand was read at, so a save somebody made since is refused as stale. The one in hand is not changed; read it again for what was saved. Supply.Create(…)hands back the saved aggregate (as Rails'createdoes): its id and version set and its state remembered, so a step of its own andSave()write only what changed —var s = await Supply.Create(…); s.Close(); await s.Save();— andSupply.Close(s)works on it as well.Supply.New(…)runs the same privateCreateand saves nothing (Rails'new): the value objects' rules, the tenant and the id are there at once;Rules()and the roles ofCreateare asked whenSave()inserts it, so a principalSupply.Create(…)would refuse cannot insert one throughNeweither. It exists for the factory namedCreate.- Several
Creates. An aggregate may write severalprivate static Create(…)overloads — the form's, and a loader'sCreate(FuelFileRow row)— and each gets itsSupply.Create(…)andSupply.New(…).Form.For(Supply.Create)needs no cast: the form is made over the first declared overload (a later one is told so by RASK188), and its method group converts to that one alone. A loader builds rows withSupply.New(row)and saves them in oneDb.Transaction, eachSave()asking its rules, its tenant,Create's roles and its events — exactly whatSupply.Create(row)asks; a refusal of any row rolls the whole load back, and the events go out once each after the commit.db.BulkInsert(…)is not that: it asks noCreateroles, and its fast path noRules()(what bulk insert asks). Createis the aggregate's ownprivate static Supply Create(…). An aggregate that writes no factory at all gets one generated from what it stores (a generated Create and Update).Updateis the aggregate's ownpublic void Update(…)— the main edit, the one a form over the whole aggregate makes. Its entrySupply.Update(id, version, …)andSupply.MayUpdateexist only for an aggregate that saysIUpdatable, asSupply.Delete(id, version)exists only for anIDeletableone.IUpdatablewithout anUpdategets one generated (below) — or, where none can be, RASK136; anUpdatewithoutIUpdatableRASK137, whose quick-fix adds it.- Every other public step —
Distribute,Close,Submit— keeps its own name and gets its entry and itsMay…whatever the aggregate says: an aggregate that is never edited as a whole may still have steps. - Two shapes side by side.
Supply.Update(id, version, …)(the static extension entry, by the type's name) andsupply.Update(…)(the aggregate's own method, on an instance) never meet: called by the type, the entry; on an instance, the method — which changes the aggregate in hand and saves nothing untilSave(). From inside the aggregate a bareUpdate(…)is always the method. - A form names them too:
Form.For(Supply.Create)andForm.For(Supply.Update, id). A factory a form takes under another name (Register,For,New) and a main edit namedChangeare RASK138 — a suggestion, an error under<RaskStrict>— whose quick-fix renames the method, its entries and every call (Fix all).
A generated Create and Update
An aggregate that is its fields — a category, a destination, a tank — needs no factory and no edit written out. One
that declares no factory gets a Create, and one that says IUpdatable and declares no Update gets an
Update, both generated from what it stores, and both entries like any other: New, the dry run, the roles, May…
and Form.For.
public sealed class Truck : Aggregate<TruckId>, IVersioned, IUpdatable, IDeletable
{
[Required, StringLength(20)] public string Plate { get; private set; } = "";
public int Axles { get; }
public string? Note { get; private set; }
public BelongsTo<Depot>? Depot { get; private set; }
public HasMany<Wheel> Wheels { get; } = [];
}
var truck = await Truck.Create("ABC-123", 3, note: "spare", depot: depotId, wheels: [new WheelRow(Pressure: 2.4m)]);
await Truck.Update(truck.Id, truck.Version, "ABC-124", 3, wheels: [new WheelRow(2.6m, Id: wheelId)]);
var draft = Truck.New("XYZ-1", 2); // the generated Create, nothing saved
- One parameter per stored property — a
{ get; }or{ get; private set; }one, in declaration order: one that cannot be null is required, one that can (string?,int?, a nullable value object) is optional, defaulting tonull. TheId, the framework's columns, a computed property, a secret and a hashed value are never one. - A
BelongsTo<Depot>?is taken as the id it holds —DepotId? depot. - Children with fields of their own —
HasMany<Wheel>— are a list of a generated row,IEnumerable<WheelRow>? wheels:public sealed record WheelRow(decimal Pressure, string? Brand = null, WheelId? Id = null)besideWheel, its values as the aggregate's are, and itsIdlast. A create adds a child per row; an update syncs them byId(HasMany.Sync): a row with a child's id updates it, a row with none adds one, a child no row names is removed — with the child's rules, a refusal underWheels[1].Pressure. Left out (null), an update leaves the children as they are. - Links — a child that is only the other aggregate's key — are the list of ids:
IEnumerable<ActivityId>? activityIds, synced as a set. - The key: a
Guid(or a typed id over one) is made, an integer is the store's, and a key only the caller has — astring, or an integerConfiguresays is never generated — is the create's first parameter,id. - The update is the whole state, as a form posts it: an optional value left out is written
null. To change one thing from code, write the step that says so. - Every rule is asked as for a written one — the value objects as they are made, the attributes,
Rules(), the store's rules — and a refusal is under the parameter's field. The roles are named by string,b.Operation("Create", roles: …), as there is no method fornameofto name. - What a default cannot set, it does not guess at: an aggregate holding a secret, a child collection that is no
HasMany, a child that holds children, or a child keyed by the caller gets neither — write itsCreate(andUpdate; RASK136 says so for anIUpdatableone). - Written wins. A
private static … Create(…)of any name, or apublic void Update(…), replaces the generated one — and a secondCreateoverload or a narrower edit is written the same way, each its own form.
Where each rule lives
Every rule has one home, and every write — an entry, a form, Find → step → Save(), New → Save() — asks it there.
The line between the homes is one principle: every business rule lives in the aggregate's code — its value
objects, its steps, its Rules() and DeletionRules() — and Configure holds only what the store enforces:
uniqueness, existence, references, the column's shape, and the one cross-aggregate lock read under the save's own
transaction, LockedBy, which is of the same family as a unique index (the
store answers it, with no race). A rule that depends on another aggregate's business state — a filed return holding
its transactions — is not a lock declared in Configure but state the held aggregate carries:
HeldBy, set by its own step and asked by its own rules.
| The rule | Where it is written | When it is asked | Where its refusal lands |
|---|---|---|---|
| A value's own shape — a length, a range, a pattern | the value object (record Litres(decimal Value) : Number(Value, Min: 1)) |
as it is made: Litres.Create(…), a form field as it is committed |
under that field (Litres, Parts[1].Quantity) |
| Rules across members of the aggregate | its protected override async IAsyncEnumerable<Problem> Rules() (what every save asks); IsNew and IsChanged(…) tell it what the save writes |
by every save, before anything is written; by a form's dry run as it is filled — every problem at once | under the member each Problem.At(…) names, or the whole form |
| Whether it may go | its protected override async IAsyncEnumerable<Problem> DeletionRules() |
by every delete — X.Delete(id, version), x.Delete(); await x.Save(); — and an editor's Delete before it asks |
under the member it names, or the whole form |
| Held by another aggregate's state — a filed return's transactions | a HeldBy the held aggregate carries, set by its own steps from the other's event, asked in its Rules() / DeletionRules() (HeldBy) |
as any rule of the aggregate: by every save and delete | the whole form |
| What a delete announces | its generated XDeleted (domain events) |
in the save that deletes it | — (raises events, refuses nothing) |
| What one step allows | the step itself: Refuse.When(…) in Close(), Update(…) |
when the step runs, in an entry or on the aggregate in hand | under the field Refuse names |
| Who may | b.Operation(…, roles: …) in its Configure; b.Writes(roles: …) for every write that names none (who may write it) |
by every write before anything is read — the entry, and the writes that are no entry: a save, X.Update(id, x => …), X.Delete(id) |
a ForbiddenException |
| What only the store knows — a name taken, a row missing, a row still referenced | IsUnique("…"), WhenMissing("…"), WhenReferenced("…") in Configure — or a function that names the row: IsUnique(taken => …), WhenReferenced<Fueling>(refs => …), WhenMissing(id => …) (data.md) — never a query in Rules(), which a second save could slip past |
by the save (the database decides; a function's row is read only once it refused, never another tenant's), and as queries by a dry run | under that field |
| That a row named is there — a reference, an id handed to a step | nothing: by default, "No such vehicle." (what a missing reference says); b.Reference(x => x.Vehicle).WhenMissing("…") for words of your own |
by the save's foreign key, no query before it; an id an entry is handed by one query per aggregate before the step; a dry run asks both | under the reference (Vehicle), the parameter (Products[2], Parts[1].Tank) |
| Closed by its parent's state, read under the save's lock — a note of a closed period | b.LockedBy(…) in Configure (LockedBy) |
by every save and every set write, the parent read in the same transaction | under the parent field, or the whole form |
Refuse.When(…) is for a step that cannot run at all — a precondition, the first refusal ends it; Rules() and
DeletionRules() tell every problem at once, as a value object's do.
An operation, run as one write
An aggregate's public methods are its operations, and each gets a static entry of the same name that runs it as
one write — the load, the method and the save in one Db.Transaction. The entries are C# 14 extension members
Rask writes beside the aggregate (SupplyOperations), so the aggregate needs no partial:
public sealed class Supply : Aggregate<SupplyId>, IVersioned, IUpdatable, IDeletable, IBelongsTo<Tenant>
{
private static Supply Create(CompanyId company, SupplyDetails details, IReadOnlyList<SupplyPartSpec> parts) => …; // the factory
public void Update(SupplyDetails details, IReadOnlyList<SupplyPartSpec> parts) { … } // the main edit (IUpdatable)
public void SetOpening(Opening opening) { … } // a step of its own
public bool IsOpen() => …; // a question: no entry
public static void Configure(EntityTypeBuilder<Supply> b)
{
b.Operation(s => s.SetOpening, roles: Roles.Admin);
b.Operation(nameof(Create), roles: Roles.Buyer);
b.Operation("Delete", roles: Roles.Admin);
}
}
var supply = await Supply.Create(company, details, parts); // generated: Create → Save(), the aggregate handed back
await Supply.Update(id, version, details, parts); // generated: Find(id, version) → Update → Save()
await Supply.SetOpening(id, version, opening); // and first: is the signed-in user an Admin?
await Supply.Delete(id, version); // IDeletable: Find(id, version) → delete
if (Supply.MaySetOpening) { … } // generated: may the signed-in user run it?
- What is an operation. A public instance method declared on the aggregate, not generic, with no
ref/out/inparameter, that returnsvoid,Task,ValueTaskor the aggregate itself (a fluentDriver Update(…)). A method that returns anything else answers a question and gets no entry; neither doRules,DeletionRules,Onor a method named like a write (Create,Find,Delete,Save,Model).Updategets its entry only on anIUpdatableaggregate; every other step gets one whatever the aggregate says. - A factory is a static method declared on the aggregate that returns it (or a
Taskof it), writtenprivate: its generated entry reaches it through an[UnsafeAccessor], andawait Supply.Create(…)asks its roles, builds the aggregate, saves it (its rules asked) in oneDb.Transactionand hands it back. A factory the caller can see —publicorinternal— would win every call over its entry, so it gets none (RASK173, an error with a quick-fix). Its roles are named withnameof(Create), which names the private method. - A delete of its own. An aggregate that can be deleted (
IDeletable,ISoftDeletes) getsawait Supply.Delete(id, version): the roles ofb.Operation("Delete", roles: …)asked (an extension member cannot be named bynameof), then the aggregate loaded at that version and deleted in oneDb.Transaction, itsDeletionRules()asked by the delete; a hiddenSupply.DryRunDelete(id, version)tries it with nothing deleted, andSupply.MayDeletesays who may. Called with no version, or with adb:,Supply.Delete(id)is still the generated write's.Ui.EditorDialog's.Delete(Supply.Delete)is built on the three. Supply.May…answers, for every operation and factory, whether the signed-in principal holds one of its roles — alwaystruefor one that names none — so a page hides or disables what the entry would refuse.- What the entry does, in order: the roles of
b.Operation(x => x.M, roles: …)are asked of the signed-in principal — any one of them admits, comma-separated as[Authorize(Roles = …)]takes them — and anyone else is aForbiddenExceptionbefore anything is read; thenFind(id, version)(a save since is refused as the form's whole-form failure), the method, andSave(), which asks the aggregate's rules. A refusal anywhere — a stale version, a rule, aRefuse.When(…)in the method — rolls the whole operation back and reaches the caller as theRaskValidationExceptiona form shows. An aggregate that is notIVersionedtakes noversion. - The ids it is handed are asked first. A parameter that is another aggregate's typed id —
VehicleId vehicle,IReadOnlyList<ProductId> products, theTankIdof each row of a list — is asked before the step runs: one query per aggregate they name, through its tenant's and soft delete's filters, and a failure under the parameter for each that is not there (Products[2],Parts[1].Tank), in the sentence a missing reference says. A null is not asked, nor a child's own id. The save does not ask again for an id found here, so an id the step writes into a reference costs that one query. - A stale version says why, when it can. Refused because the version moved on, the entry runs the same step as a
dry run on the aggregate as it now stands, saving nothing: when the step refuses there — its
Refuse.When(…),Rules()orDeletionRules(), a store rule — that refusal is the answer ("This period is already closed."), a row deleted meanwhile says Someone else deleted this in the meantime., and only a step that would go through keeps the concurrency refusal. So a step must be pure: it changes its own aggregate and calls nothing outside it (optimistic concurrency). - Tried, not done:
Supply.DryRunUpdate(id, version, …)(hidden; a factory's isDryRunCreate(…)) runs the operation on a fresh copy of the aggregate and asks the rules a save would — the changed properties' attributes,Rules(), aRefusein the method, a stale version — and hands back everyFieldFailureunder the field it names, empty when it would go through. It asks what only the store would refuse too, as queries and never as a write: eachIsUnique("…")rule a new or changed column touches (one query per rule, none for a column the operation leaves as it was), each reference it sets to another tenant-scoped table (WhenMissing, one query per table) — so "Már van ilyen név" is shown as the name is left — and, forDryRunDelete, a row that still points at the aggregate through a relationship with a sentence (WhenReferenced("…"),OnDelete(behavior, "…")). Nothing is written, no version bumped, no event published, and aDb.Lockinside the rules is not taken. It is what a form over the operation asks while it is filled in, so the rules the form shows are the domain's own. - The roles are read where the entry is generated, as
[Authorize(Roles = …)]is read by the compiler: written in the aggregate's own staticConfigure, the operation as a lambda and the roles as a constant. Anywhere else the entry would ask nothing, so the build stops (RASK172). A step's roles are asked by its entry; the method called on an aggregate in hand is your own code and runs as written — but itsSave()asks the roles of every write (who may write it). - Two aggregates, or a row held while it runs:
b.Operation(x => x.M, manyAggregates: "why")runs the entry inDb.Transaction(…, manyAggregates: "why")(one aggregate per transaction);forUpdate: truereads the aggregate's row under an update lock before the load, andforUpdate: s => s.Partsthe rows of that child collection —UPDLOCK, HOLDLOCKon SQL Server,FOR UPDATEon PostgreSQL, nothing more on SQLite, whose one writer serializes already — so a second operation on the same rows waits for the first to commit instead of being refused as stale. The reason is a constant, read like the roles. In a static method of your own,await id.Load(version, forUpdate: true)does the same: generated on a typed id that one aggregate alone is keyed by, it loads the aggregate whole (KeyNotFoundExceptionwhen there is none, the stale-version refusal asFind(id, version)), and refuses a lock outside aDb.Transaction, which would hold nothing. - A job or an event handler, which read no version:
await Supply.Update(id, details, parts)— the same entry without theversion, generated beside it for anIVersionedaggregate — loads the aggregate as it now stands and runs the operation on that, its roles and rules asked as ever. It is the system actor's call (a rematch, an ingest), never a form's: a person changes what they read. An operation whose first parameter takes a number (Book(int seats)) gets none, sinceSupply.Book(id, 3)would read both ways — pass the version it loaded. - Inside the aggregate, a bare call is the method. The entries are extension members, which a bare
Update(…)written inSupplynever reaches;Supply.Update(id, version, …)by the type's name is the entry, and saves another copy. An operation whose parameter is namedid,versionorcancellationTokengets no entry (RASK171). - Outside the aggregate, call the entry, not a context.
db.Products.Add(Product.Place(…))ordb.Update(product)followed bySaveChangesAsync()writes the aggregate past its roles and its rules (RASK133);await Product.Place(…)andawait Product.Reprice(id, version, …)are the same write through the aggregate, and a check that must go with it is aDb.Transactionaround the operation.
Who may write it
Each write asks the roles Configure names for it, and a write that names none asks the roles of every write of
the aggregate — b.Writes(roles: …), or [WrittenBy("…")] on a base class or an interface it implements. A catalog
row every tenant reads but only an administrator changes says it once:
public sealed class Supplier : Aggregate<SupplierId>, IVersioned, IUpdatable, IDeletable
{
public void Rate(Stars stars) { … }
public static void Configure(EntityTypeBuilder<Supplier> b)
{
b.Writes(roles: Roles.Admin); // Create, Update, Delete, every step, every save
b.Operation(s => s.Rate, roles: Roles.Customer); // …but a customer rates it
}
}
| The write | The roles it asks |
|---|---|
X.Create(…), Form.For(X.Create), and every insert: X.New(…) then Save(), X.Create(x) |
Create's, else every write's |
X.Update(id, version, …), Form.For(X.Update, id), X.Update(x, …), X.Update(id, x => …) |
Update's, else every write's |
X.Delete(id, version), X.Delete(x), X.Delete(id), x.Delete() then Save() |
Delete's, else every write's |
a step's entry X.Rate(id, version, …) and its Form.For |
the step's, else every write's |
Save() of an aggregate loaded by X.Find(id) and changed by its own methods |
every write's |
- Before anything is read. A principal holding none of the roles is refused with a
ForbiddenExceptionbefore the row is loaded or anything is written;X.May…answers the same question for a page. - An entry asks once. The save an entry ends in does not ask again, so a step open to more than the aggregate's
other writes (
Rateabove) stays open through its own entry — whileFind→Rate(…)→Save()asks every write's roles, as a save cannot tell which steps ran. roles: ""opens one write to anyone underb.Writes.b.WritesinConfigureoverrides an inherited[WrittenBy].- A dry run asks none.
DryRun…and a form's checks write nothing; the entry asks the roles when it runs. - Not asked:
BulkInsert(a seed or a migration, data-writes), and the rawDbContext, which RASK133 keeps out of app code. - A job has no principal, so it is refused a write that names roles: run it as the user it acts for
(
Current.UsePrincipal(…)), or give the write it needsroles: "". - A name no write takes is an error. Roles for
Save,Find, a question, a method that does not exist, or theDeleteof an aggregate that cannot be deleted would be asked by nothing (RASK214).
Refusing an operation: Refuse
An operation that cannot go ahead says so with Refuse, never with an exception of its own: it throws a
RaskValidationException, which a form shows like any failed rule — the message under the field it names, or above
the form when it names none — and an API caller gets as a 400 with errors. The same is true of a test, where
Test.Refuses asserts the field.
public void Ship(TrackingNumber tracking, ShipDay shippedOn)
{
Refuse.Unless(Status == OrderStatus.Paid, $"A {Status} order cannot ship."); // the whole form
Refuse.When(shippedOn < PaidOn, () => shippedOn, "An order ships after it is paid."); // under "ShippedOn"
(Status, Tracking, ShippedOn) = (OrderStatus.Shipped, tracking, shippedOn);
}
for (var i = 0; i < Parts.Count; i++)
{
Refuse.When(locked.Contains(Parts[i].Id), () => Parts[i].Quantity, Texts.LockedChanged); // "Parts[2].Quantity"
}
- A broken invariant is no refusal.
Refuseis for what the person at the screen can act on. A state the aggregate's own methods never let it reach is a programming error: throwSystem.Diagnostics.UnreachableException, which RASK184 leaves alone, and it reaches the logs as the bug it is. Refuse.When(condition, …)refuses when the condition holds,Refuse.Unless(condition, …)when it does not, andRefuse.At(() => field, message)always — the branch that already knows. Each takes the field as a lambda, or no field for the form as a whole.- The field path is read from the lambda, as the form names it:
() => Km.StartisKm.Start; an index is evaluated, so() => Parts[i].QuantityisParts[2].Quantity; a captured local or parameter takes its form field's name (() => parts[i].QuantityisParts[2].Quantity);this.is dropped. A lambda that is not a chain of members and indexers (() => Total()) throws anArgumentExceptionnaming the shape to write. - The lambda is read only when the operation is refused. A call that goes through pays for the expression the compiler builds at the call site and nothing more, so a guard in a loop over thousands of rows stays cheap.
- A child row's own key, rather than its index, is
Problem.At(child)'s to give, from a value object's rules. - A problem inside a list a value or an aggregate holds names its path the same way, positions evaluated:
yield return Problem.At(() => LocalWells[i].Companies[j].DbId, Texts.NotThisPartners)is underLocalWells[2].Companies[0].DbId— where the form shows that row's field.Problem.At(member, …)without a lambda keeps the member as written.
Find, change, Save
When the change is the aggregate's own method, load it, call it, save it:
var order = await Order.Find(id) ?? throw new KeyNotFoundException();
order.Ship("1Z999");
await order.Save();
await Order.Place("A-1001").Save(); // a new aggregate is inserted
It works the way Rails' and Laravel's models do: Find reads the row once and remembers what it read, and Save()
writes what changed since — it never reads the row again.
- Read once.
Findloads the aggregate whole, through a context of its own, and hands it back detached with a snapshot of what it read.Save()compares with that snapshot and writes only the columns you changed — a column someone else changed meanwhile keeps their value — with no SELECT, however large the row. Every successful save takes a new snapshot, so the nextSave()reads nothing either. - New is inserted with no read. An aggregate your code made (
Order.Place(…),new() { Id = Uuid.Create() }) and never saved is an INSERT. So an aggregate built — or deserialised — with the key of an EXISTING row is an insert too, refused by the key:Findit and change it instead. - Children are synced by id. A child you added is inserted, one you removed is deleted, one you changed is updated.
- Changed underneath is refused, never written over. The
Versioncompared is the oneFindread, so on aIVersionedaggregate a save after someone else's — or after a soft delete, which bumps it — is refused with the whole-formRaskValidationExceptionabove. So is a save whose row, or a changed child's, has been deleted outright: nothing is silently re-inserted. An aggregate with noVersionthat saysISoftDeletesis asked first whether its row is still there (by its key alone — one small SELECT), and isKeyNotFoundExceptionwhen it is not. - The domain is asked first — the changed properties' attributes,
Rules(),DeletionRules()— and a save it refuses is aRaskValidationExceptionwith nothing written, stamped or versioned (what every save asks). - The interceptors run as for any write: times stamped,
Versionbumped, tenant checked, domain events published after the commit. - Nothing is held open.
Findtakes nodb:and returns the aggregate untracked, so it is safe to keep in a page field betweenFindandSave. Passdb:toSaveto stage it in your own unit of work; its snapshot is taken when that context'sSaveChangesAsyncsucceeds. - Delete what you found:
file.Delete(); await file.Save();—var file = await QueuedFile.Find(id); if (file.Expired) { file.Delete(); await file.Save(); }.Delete()marks it and the save deletes it, itsDeletionRules()asked then. Like Rails'record.destroyand Laravel's$model->delete()it works from whatFindread, with no read first: an aggregate that saysISoftDeletesis stamped, any other has its row and its children removed. TheVersionread is compared, so a row changed or deleted since is the same whole-form refusal (an unversioned soft-deleting one is asked by its key first,KeyNotFoundExceptionwhen gone); one never saved isInvalidOperationException. It takesdb:likeSave, and insideDb.Transactionit is written in the transaction — a rollback leaves the row and its children, and its events go out after the commit. The staticQueuedFile.Delete(id)stays, and loads the row first. - Only to show it? Do not
Findit. A list, a detail page or a check reads the read face (Order.Where(…)); an edit form isForm.For(Order.Update, id), which reads it itself.Findis for changing the aggregate through its own methods.
Order.Update(id, o => o.Ship("1Z999")) does the same in one call when there is nothing to show in between.
What every save asks
Every save — Save(), Update(id, apply), an entry such as Create(…), Delete, a db: context you save yourself — asks the
domain before anything is written. A rule is written once, on the aggregate, and holds however the row is changed:
public sealed class Voyage : Aggregate<Guid>, IVersioned, IDeletable
{
private readonly List<Leg> _legs = [];
[Required, StringLength(80)] public string Title { get; private set; } = ""; // a DataAnnotations rule
public bool Sealed { get; private set; }
public IReadOnlyCollection<Leg> Legs => _legs;
public void Seal() => Sealed = true;
protected override async IAsyncEnumerable<Problem> Rules() // the aggregate's own rules, over its rows
{
if (Sealed && _legs.Count == 0) yield return Problem.At(Legs, "A sealed voyage needs a leg.");
}
protected override async IAsyncEnumerable<Problem> DeletionRules() // asked by a delete, in its place
{
if (Sealed) yield return Problem.Whole("A sealed voyage stays.");
}
}
For every row the save adds or changes, in this order:
- The validation attributes of its properties — every one on a new row, but on a stored row only the properties
this save changes. A row stored before a rule was tightened still opens, and still saves for another field; the
rule is asked again once that field is touched. A one-value value object is checked by the value it holds, as its
form field is.
The rules it states in code — a FluentValidation
RuleForin its ownstatic void Rules(InlineValidator<T> rules)or in anAbstractValidator<T>class (forms validation) — are asked the same way,MustAsyncincluded: every rule of a new row, only the changed members' of a stored one. - Its type's attributes, and
IValidatableObject/IAsyncValidatableObjectwhen it implements one. - Its
Rules()— the root's whenever anything in the aggregate changes, a removed row included, because a rule over the rows is the root's.
A deleted aggregate is asked its DeletionRules() instead. Both are overrides of Rask's bases —
protected override async IAsyncEnumerable<Problem> Rules() and DeletionRules() — every problem yielded at once,
Problem.At(member, "…") or Problem.Whole("…"), so the aggregate needs no partial and nothing is found by name.
Why async, when a value object's Rules() is not: a value object is pure — it knows only what it holds — while an
aggregate's rule may have to ask the store; one shape serves both, and a body that awaits nothing needs no await
(the compiler does not ask for one). One that awaits passes Current.Cancellation. Whether a row
exists, is taken or is still referenced is the store's to say, in Configure — IsUnique("…"),
WhenMissing("…"), WhenReferenced("…") — where no second save can slip between the question and the write; a
query in Rules() is for what cannot be said that way. A Validate() or ValidateDelete() found by its name is asked
no more: RASK203, an error whose quick-fix makes it the override, its body kept (Fix all).
What the save writes, asked from inside. A rule that depends on the write — not on the state alone — asks the aggregate's own protected members, which answer only while the save asks its rules (anywhere else they throw):
Asked inside Rules() / DeletionRules() |
True when |
|---|---|
IsNew |
the save inserts the aggregate |
IsChanged() |
the save changes anything of it — a new aggregate changes everything, a deleted one nothing |
IsChanged(() => Quantity), IsChanged(() => Quantity, () => Lines) |
the save changes one of those members |
IsChanged(except: () => HeldBy) |
the save changes a member other than those |
A member is the aggregate's own, written as () => Member (as Refuse.When(…, () => Title, …) names one): a column,
a BelongsTo (HeldBy, not its column HeldById), a value object (() => Total.Amount asks about Total), or a
collection of children, changed when a row of it is added, changed or removed. A value set back to what was read is
no change; the key, Version, the stamps and the tenant are the save's own bookkeeping, never one.
What they refuse is ONE RaskValidationException, with every failure under the field a form over the entry names —
Title, Legs, Legs[2].Port — and a built-in attribute worded as DataAnnotations words it, so a form that
lets the exception through shows each message under its field. It is asked first of every save step, so a refused
save has been stamped and versioned by nothing: fix the value and Save() again. A rule resolves services from the
request, live session, handler or job in progress (validationContext.GetService<T>()). BulkInsert is not a
Create: it never asks Create's roles, and its fast path (SkipChangeTracking) runs no interceptor, so it asks no
Rules() either (what bulk insert asks).
A row closed by its parent: LockedBy
A delivery note of a closed period, a transaction of a filed return: the row stays as it was while the row it
belongs to says so. Declare it once in Configure, and every save holds to it — a page's, a job's, an import's:
public static void Configure(EntityTypeBuilder<DeliveryNote> b) =>
b.LockedBy(n => n.Period, (Period p) => p.Closed, Texts.PeriodClosed);
public static void Configure(EntityTypeBuilder<GasClaim> b) => // the words made from the parent
b.LockedBy(c => c.Period, (Period p) => p.Closed, p => $"{p.Name} is closed.", LockRead.ForUpdate);
n => n.Period is the property holding the parent's key — a typed id, an int, a nullable one — and
(Period p) => p.Closed is translated to SQL, so it may reach further (r => r.Filings.Any(f => f.UnfiledAt == null)).
The save asks it with the rest of what every save asks, one query per lock for all the rows
of the save:
- The old and the new parent. For a row the save adds, changes or deletes, the parent it was read with and the one it holds now are both read, so a row is moved neither out of a locked parent nor into one. A null key names no parent and locks nothing; a null set to a locked parent is refused.
- A child's change locks through its root. A line added to, changed on or removed from a note of a closed period is refused as the note would be: the aggregate is the unit the lock holds.
- Under the parent field, or the whole row. A new row, or one whose parent the save changes, is refused under
that field (
Period); any other write is refused about the row itself — the whole form for a root. LockRead.ForUpdatereads the parents with an update lock held to the end of the save —UPDLOCK, HOLDLOCKon SQL Server,FOR UPDATEon PostgreSQL, nothing on SQLite, whose one writer serializes the save already — so a "Close period" cannot slip in between the check and the write. The save runs in a transaction of its own when its caller opened none (insideDb.Transaction, it is that one). On a context whose execution strategy retries — Rask.SqlServer's and Rask.Postgres's by default — Rask's own writes (order.Save(),X.Create,X.Update,X.Delete, an operation's entry, an import) run the save inside the strategy with that transaction, so the locked read and the write commit together and a transient failure retries them together. ASaveChangesof your own on such a context opens none: put it inDb.Transactionfor the lock to hold.
The parents are read past every query filter, so a soft-deleted closed period still holds its notes. A parent the same save closes is judged as the database has it, before this save.
Columns a lock lets through, and words for each write. A filed return holds its transactions, but a claim may still take one over by its refund columns; and "deleted" and "changed" want different sentences, which may name something the parent holds:
public static void Configure(EntityTypeBuilder<Transaction> b) =>
b.LockedBy(t => t.RefundId, (Refund r) => r.Filings.Any(f => f.UnfiledAt == null),
(r, write) => write.Kind == LockedWriteKind.Delete
? $"{r.Name} is filed at {r.Filings[0].Office}: it keeps its transactions."
: $"{r.Name} is filed at {r.Filings[0].Office}: {write.Row.Litres} litres stay as filed.")
.Except(t => t.RefundId, t => t.ForeignRefundId) // a change to only these passes, under a filed refund too
.Including(r => r.Filings); // loaded with each locked parent, for the words
Except(columns)lets a change through when every column it touches is one of these — even the parent key, so a claim moves the transaction. An add, a delete, a change to any other column, and a change through a child are still refused.- The message
(parent, write)is told the write'sKind—Add,Change,DeleteorMove(a new parent) — and itsRow, as the save would write it. Including(p => p.Navigation)loads that navigation of each locked parent before the message reads it; without it the parent comes back as its own columns only.
A row held by another aggregate: HeldBy
A transaction a filed gas-refund return claims stays as it was filed — but "filed" is the return's business state, not the database's. So the held aggregate carries it as state of its own, changed only by its own steps, and its own rules hold to it:
public sealed partial class Transaction : Aggregate<TransactionId>, IVersioned, IDeletable
{
public decimal Litres { get; private set; }
public BelongsTo<GasReturn>? HeldBy { get; private set; }
public void Correct(decimal litres) => Litres = litres;
public void HoldFor(GasReturnId filed) => HeldBy = filed; // its own steps — and the only ones that touch HeldBy
public void Release() => HeldBy = null;
protected override async IAsyncEnumerable<Problem> Rules()
{
if (HeldBy is not null && IsChanged(except: () => HeldBy))
yield return Problem.Whole("A filed return holds it: it cannot change.");
}
protected override async IAsyncEnumerable<Problem> DeletionRules()
{
if (HeldBy is not null) yield return Problem.Whole("A filed return holds it: it cannot be deleted.");
}
// The return's step raises ReturnFiled; the transactions take hold in their own steps — another aggregate's
// step, then its event, then this aggregate's own step, in a handler on the aggregate it changes.
static Task On(ReturnFiled e) => Transaction.UpdateEach(t => e.Transactions.Contains(t.Id), t => t.HoldFor(e.Return));
static Task On(ReturnWithdrawn e) => Transaction.UpdateEach(t => t.HeldBy == e.Return, t => t.Release());
}
- Every write holds to it, whoever makes it — a page, a loader, a job:
Rules()refuses any change butHoldFor/Releasethemselves while the row is held,DeletionRules()refuses the delete, and a change through a child (IsChangedcountsLines) is a change too. - A set write cannot skip it:
X.UpdateWhereon an aggregate that overridesRules(), andX.DeleteWhereon one that overridesDeletionRules(), are refused and name the path that asks —UpdateEach,Delete(id)(writes over many rows). - It reads as the domain says it:
HeldByis a column a page can show and a query can filter (Transaction.Where(t => t.HeldBy == null)), with no join through the other aggregate's tables. - When to choose
LockedByinstead: the row's parent already says it (Period.Closed) and the lock must be read in the save's own transaction — a close racing a write.LockedByis the parent shortcut the store enforces,HeldBythe general pattern: another aggregate's step, its event, this aggregate's own step.
Behaviour-rich aggregates
An aggregate whose state moves through steps is the usual shape, not a special one. An order is placed, paid, shipped or cancelled; an invoice is never deleted, it is voided, and a mistake is corrected by a credit note. Each step is an operation, each refuses what it does not allow, and nothing else can change the aggregate:
public enum OrderStatus { Placed, Paid, Shipped, Cancelled }
public readonly partial record struct OrderId(Guid Value);
public sealed partial record OrderReference(string Value) : Text(Value, MaxLength: 40, Upper: true);
public sealed partial record TrackingNumber(string Value) : Text(Value, MaxLength: 60, Trim: true);
public sealed partial class Order : Aggregate<OrderId>, IHasTimestamps, IVersioned // a factory, no IUpdatable, no IDeletable: operations only
{
public OrderReference Reference { get; private set; }
public OrderStatus Status { get; private set; }
public TrackingNumber? Tracking { get; private set; }
private static Order Place(OrderReference reference) => // the factory: Order.Place(reference)
new() { Id = OrderId.Create(), Reference = reference, Status = OrderStatus.Placed };
public void Pay()
{
Refuse.Unless(Status == OrderStatus.Placed, $"A {Status} order cannot be paid.");
Status = OrderStatus.Paid;
}
public void Ship(TrackingNumber tracking)
{
Refuse.Unless(Status == OrderStatus.Paid, $"A {Status} order cannot ship.");
(Status, Tracking) = (OrderStatus.Shipped, tracking);
}
public void Cancel()
{
Refuse.Unless(Status is OrderStatus.Placed or OrderStatus.Paid, $"A {Status} order cannot be cancelled.");
Status = OrderStatus.Cancelled;
}
}
OrderId id = await Order.Place(OrderReference.Create("a-1001")); // the factory decides what a new order is
await Order.Pay(id, version); // load whole, run the rule, save
await Order.Ship(id, version, TrackingNumber.Create("1Z999")); // a stale version is refused
A page binds each step to a form or a button — Form.For(Order.Ship, id) asks for the tracking number and shows
A Placed order cannot ship. at its top before anything is saved — and when a page shows the order between loading
and changing it, the same rules run through Find and Save.
- Only the methods are callable. The properties have private setters (RASK084), so
nothing outside the aggregate sets
Statuswithout going throughShip. Each entry is one unit of work: the aggregate is loaded with its children, the method runs, the version is checked, and any events it raises are saved in the same transaction. - A factory of its own and no
IUpdatablemean nothing is generated. A generatedCreateorUpdatesets each stored property directly, which is right for a category and wrong here: it could setStatuswithout going throughShip. WritingPlacereplaces the generatedCreate, and leavingIUpdatableoff means there is noUpdate. The forms of an aggregate like this are its operations' (a form over an operation). - No
IDeletablemeans noDelete.Order.Delete(id)is then a compile error. Retiring an order isCancel, which keeps the row, its history and everything that refers to it.
Time in the domain
Time in Rask is always UTC, and has one source: Clock.Now, now in UTC (a DateTimeOffset at offset 0).
Clock.Today is today's calendar day in the app's zone and Clock.Zone the zone itself
(AddRask(timeZone: "Europe/Budapest"), c.TimeZone on a RaskApp) — the zone people read time in, used only to
show a moment (Format.Moment, the Ui components), to take one in (FromWall), and for a day. There is no
"wall-clock now". A test's Clock.Fake(at: …) freezes all of them, together with the audit stamps, the jobs' schedule
and 3.Days.Ago; it freezes nothing that reads DateTime.Now.
public void Stamp() => ModifiedAt = ModifiedMoment.Create(Clock.Now.UtcDateTime); // not DateTime.Now
public string Shown => Format.Moment(ModifiedAt); // not .ToLocalTime()
DateTime.Now, Today, UtcNow, DateTimeOffset.Now/UtcNow and .ToLocalTime() in domain code are
RASK140, whose quick-fix writes the Clock read of the same type.
Moment and Day
There is one way to hold time in the domain: a Moment for an instant — when something happened, stored as UTC
on every database — and a Day for a calendar day — a due date, a birthday, a day a price list starts, with no
time of day and no zone. An aggregate, an entity, a value object, a domain event or a read model holds no bare
DateTime or DateTimeOffset.
public sealed partial record FuelingMoment(DateTime Value) : Moment(Value, NotAfterNow: true);
public sealed partial record DueDay(DateOnly Value) : Day(Value);
public FuelingMoment FueledAt { get; private set; }
public DueDay Due { get; private set; }
A moment is UTC; local time is for people and devices only. Compute with .Utc (b.At.Utc - a.At.Utc, <, >),
group by .Day (the day in Clock.Zone), show with Format.Moment(m) / Format.Day(m), and send a device its local
time with .WallIn(zone). A Ui.DayAndTime or Ui.DatetimePicker bound to a moment (or a UTC DateTime) shows it
in Clock.Zone and turns what is typed back into UTC by the rule below; an Excel export (Rask.Xlsx) writes a UTC
DateTime or DateTimeOffset cell in Clock.Zone too, the reader's view.
A wall-clock time from outside becomes a moment where it comes in. A pump, a tachograph or a CSV that writes its local time without an offset is read at the boundary and made an instant there, never kept as it was written:
var at = FuelingMoment.FromWall(reading.LocalTime, pumpZone); // the pump's own zone
var here = FuelingMoment.FromWall(row.Time); // the app's, Clock.Zone
FromWall follows one fixed rule for the two hours a year a wall time is not one instant — the rule SQL Server's
AT TIME ZONE follows, so a conversion done in SQL agrees with the app:
| Wall time | In Europe/Budapest | Becomes |
|---|---|---|
| shown twice, when summer time ends | 2026-10-25 02:30 |
its first occurrence, still in summer time: 00:30Z |
| skipped, when summer time begins | 2026-03-29 02:30 |
moved forward by the jump: 03:30+02:00, 01:30Z |
The first occurrence is the earlier instant, so a reading made then is never later than it was. A moment made from
its instant — a UTC DateTime, a text with Z or an offset, a row read back — keeps it exactly, either side of the
change: the two 02:30s of an October night are two moments, ordered as they happened.
Going back out: .Utc is the instant, .Day its day in Clock.Zone, Format.Moment(m) what a person reads, and
.WallIn(zone) the wall clock of a zone — what a device that keeps its own local time is sent. ToString() writes the
instant as ISO 8601 with its Z (2026-10-25T00:30:00Z), which Parse reads back; Parse of a text without an
offset reads it on the clocks of Clock.Zone, as FromWall does.
On the wire and in JSON a moment is its instant. The generated CQRS codec, the API client and System.Text.Json
(a job's stored command, an outbox message, persisted state, an API body) all write it as the UTC instant with its
Z — "2026-10-25T00:30:00Z" — so both 02:30s of that October night arrive as the
moments they were. The value object generator gives each record declared from Moment its own
[JsonConverter] for that (System.Text.Json reads none off a base type); one the record names itself wins. Read, a
text with Z or an offset is the instant it names, and one without is the form written before moments travelled as
instants (a job stored then), a wall-clock time of Clock.Zone, read so. The object an older System.Text.Json wrote,
{"value":…,"instant":…}, is still read for one release, through its instant. What the UI shows — a picker, Format.Moment — is in Clock.Zone.
Rask obeys the same rule. The stamps it writes on every entity — CreatedAt, UpdatedAt, DeletedAt — and the
times of its own tables (a job's RunAt, a session's ExpiresAt) are a Timestamp, the framework's own Moment:
order.CreatedAt.Utc, order.CreatedAt.Day, Timestamp.Now. An app's moments stay its own types, with the bounds
its domain says.
Services stay outside the domain
The domain decides from the state it holds and what its caller hands it. A service it would need — a price list, an
exchange rate, the mail sender — is the caller's to use: pass what it answered into the operation
(order.Price(sku, prices.Of(sku))), or raise a domain event and let its
handler use the service. Current.Service<T>() inside an aggregate, an entity or a value object is
RASK141.
Keeping state inside the aggregate
State changes only through the aggregate's own methods, which keeps its invariants and its domain events in one place. The build holds that line:
- No public setters (RASK084, an error). A public
set, a hand-written publicinitor a public mutable field on an aggregate, an entity (or an abstract base the app puts between them) or a value object one of them holds is refused, with a lightbulb that makes itprivate. EF Core and the generated writes both work through private setters. A positional record's parameters are exempt, sorecord Money(decimal Amount, string Currency)is never reported. - No mutable collections of entities (RASK085). A navigation to many entities is exposed read-only, over a private field EF Core maps, and changed through a method. The lightbulb rewrites it:
public sealed class Order : Aggregate<Guid>
{
private readonly List<OrderLine> _lines = [];
public IReadOnlyCollection<OrderLine> Lines => _lines;
public void AddLine(Guid productId, int quantity) => _lines.Add(OrderLine.For(productId, quantity));
}
public sealed class OrderLine : Entity<Guid>
{
public Guid ProductId { get; private set; }
public int Quantity { get; private set; }
public static OrderLine For(Guid productId, int quantity) =>
new() { Id = Uuid.Create(), ProductId = productId, Quantity = quantity };
}
The entity owns its key. Rask.Data's key convention leaves an integer key (or a typed id over one) to the database's identity and
marks every other key never generated, so a Guid or a strongly-typed id is assigned where the entity is
built: Id = Uuid.Create() (or a typed id's Create()) in its factory. That is what lets a child with an id of its own be added
to a loaded aggregate and saved as an insert. An entity added with its key still at the default is refused at
the save, by name, rather than inserted with an empty key. A key you configured yourself
(ValueGeneratedOnAdd(), a database default) is left as you set it, and an integer key you marked
ValueGeneratedNever() is yours to assign like the rest: 0 is refused, and the aggregate takes its key
in Create(id, …).
One aggregate refers to another by id. Order holds a Guid ProductId, not a Product: each aggregate is
loaded and saved on its own, and a change that spans two follows from an event — or, as the last resort, is saved with it in one transaction.
Domain events
Two kinds of event say what happened to an aggregate, and one shape hears them all.
Automatic — the lifecycle. Every aggregate X has three events generated beside it, raised by every save that
writes it — a generated entry, Find → change → Save, a form, a dialog, db.Remove(x) — after its rules passed, stored
and published with the save, never on a rollback:
| Event | Raised when | Carries |
|---|---|---|
XCreated(XId Id) |
a save inserts it | its id — the store's own, when the store makes the key |
XUpdated(XId Id, Changes<X> Changed) |
a save really changes it — a member's value, or a child added, removed or changed | what changed, and what it was |
XDeleted(XId Id, XRead Was) |
a save deletes it (a soft delete too) | its row as it was: columns, value objects, children |
static Task On(SupplyUpdated e) =>
e.Changed.Has(s => s.InvoiceNumber) // what changed…
? Ledger.Rebook(e.Id, from: e.Changed.Was(s => s.InvoiceNumber)) // …and what it was
: Task.CompletedTask;
- Published only when something hears it. The build knows every
On(E)of the app and of what it references; a lifecycle event nothing handles is never made, never stored, and costs a save nothing. XUpdatedonly for a real change. A save that writes the same values, or only its own bookkeeping (version, stamps, tenant), raises none.Changed.Has(s => s.Lines)is true when a line was added, removed or changed;Changed.Was(…)reads a column, a value object or a collection of values as it was — a child collection carries no old value.- A bulk
ExecuteUpdate/ExecuteDeleteraises nothing: no row is loaded, so nothing is known to have changed. A prune of an aggregate whoseXDeletedis heard is refused at boot for that reason. - The names are the app's to take: a type the app declares as
XCreatedkeeps the name, and that one is not generated (RASK202).
Custom — a business fact. What the domain means is said by the aggregate, with Raise(…) inside an operation —
Raise(new SupplyClosed(Id)) — under its own name, carrying the id and the small facts a handler needs, never the
aggregate itself (RASK212). An event a factory raises reads the id as it is then, so key the
aggregate on the client: a store-generated key is still 0 there
(RASK145); XCreated waits for the store's key by itself.
Hearing one — On(E e), wherever it belongs:
public sealed class Tank : Aggregate<TankId>
{
static Task On(SupplyCreated e) => Tank.Refill(e.Id); // changes THIS aggregate, through its entry
}
public static class SupplyMail // side effects: a plain static class
{
static Task On(SupplyClosed e, IMailer mail) => mail.Send(…); // services are parameters, resolved per call
[Job(Lane = "nav")] // long work: a job
static Task On(SupplyDeleted e, INav nav, CancellationToken ct) => nav.Revoke(e.Id, ct);
[Immediate] // in memory, after the commit
static Task On(SupplyUpdated e, IPriceCache cache) => cache.Forget(e.Id);
}
public sealed partial class SupplyList : Component
{
void On(SupplyClosed e) => StateHasChanged(); // every open page that has it mounted
}
- Durable by default. A
static Task On(E e, …)on an aggregate or a static class gets an outbox row in the transaction that raisedE, and runs from there after the commit in a transaction of its own — exactly once for the database (the inbox), retried with backoff, dead-lettered and replayed from the dashboard; events of one aggregate reach it in the order raised. A call outside the database namese'sDurableEvent.Current.MessageIdas its idempotency key. [Immediate]runs it in memory straight after the commit, for what can be rebuilt — a cache, a counter. It is lost if the process stops in between.[Job(Lane = …, TenantLane = …, LaneOf = …, UnlessWaiting = …, Uninterruptible = …)]hands it to a job: an import, a pull from a partner.- On a component, an instance
On(E e)(returningvoidorTask) is heard by every open page that has the component mounted, in that page's session. - On an aggregate it changes that aggregate, through its entry, without a version (the aggregate as it now stands); another aggregate is changed by its own entry, never by a method called on an instance the handler loaded (RASK205). Write it so a second run is harmless.
- Its shape is checked at build (RASK179).
IEventHandler<T>,IDurableHandler<T>and theOnDelete()hook are retired, each with a quick fix (RASK204, RASK206). - State made from rows — a running number, a total another table keeps — is declared rather than handled: a
Projects(…)raises the event in the save that changed the rows, andNumbered(…)keeps a running number with no event at all. - Live pages refresh by themselves: a save of an aggregate a live query reads refetches it on every page reading it (staying fresh) — nothing to declare.
- In a test,
using var events = Events.Fake();records what the saves raised — every lifecycle event too, heard or not —events.Raised<SupplyClosed>().Once(), andawait Events.Deliver()runs the handlers, the durable ones inline (testing).
Compared:
| Rails | Laravel | Rask | |
|---|---|---|---|
| lifecycle | callbacks after_create/update/destroy |
model events created/updated/deleted |
generated XCreated/XUpdated/XDeleted |
| custom | Wisper / RES gems | event(new X) |
Raise(new X(Id)) in an operation |
| subscribe | callbacks / subscribers | Listener, Observer, Subscriber (auto-discovered) | static On(E, services) anywhere |
| delivery | after_commit + job (can be lost) |
ShouldDispatchAfterCommit + ShouldQueue (can be lost) |
outbox, never lost |
| dedup / order | none | none | inbox by default, per-aggregate order |
| what changed | saved_change_to_x? |
wasChanged('x') |
e.Changed.Has(s => s.X) / Was(…) |
| live UI | Turbo broadcasts_refreshes |
Echo broadcasting | automatic from the saves |
| test | assert_enqueued_jobs |
Event::fake |
Events.Fake() / Events.Deliver() |
Forms over an aggregate's entries
A form writes through an entry, and its fields are that entry's parameters: Form.For(Product.Create) is a form whose
fields are what Create takes, Form.For(Product.Update, id) one whose fields are what Update takes, filled from the
stored product. The layout is the page's own markup — which fields, in what order, under which labels — and two forms
that ask for different things are two entries: a second Create overload, a step of their own.
public sealed class Product : Aggregate<ProductId>, IHasTimestamps, IVersioned, IUpdatable, IDeletable
{
[Required, StringLength(80)] public string Name { get; private set; } = "";
public Money Price { get; private set; }
public string? Notes { get; private set; }
}
Product writes neither a Create nor an Update, so it gets both, generated from what it
stores: Product.Create(name, price, notes) and Product.Update(id, version, name, price, notes). A create page binds the first:
[Route("/products/new")]
public sealed partial class NewProductPage : Component
{
protected override Component Render() =>
Form.For(Product.Create).OnSaved(GoBack)[f => [
Ui.Input.Bind(() => f.Name).Label("Name"),
Ui.Input.Bind(() => f.Price.Amount).Label("Price"),
Ui.Textarea.Bind(() => f.Notes).Label("Notes"),
Ui.Button.Submit.Disabled(f.Submitting)["Create"],
]];
}
An edit page binds the second, with the route's id — the fields start from the stored product, each read off the property of its name, and the version it was read at rides along, so a save since is refused at the form's top:
[Route("/products/{id}/edit")]
public sealed partial class EditProductPage : Component
{
[RouteParam] public ProductId Id { get; set; }
protected override Component Render() =>
Form.For(Product.Update, Id).OnSaved(GoBack)[f => [
Ui.Input.Bind(() => f.Name).Label("Name"),
Ui.Input.Bind(() => f.Price.Amount).Label("Price"),
Ui.Textarea.Bind(() => f.Notes).Label("Notes"),
Ui.Button.Submit["Save"],
]];
}
- The fields are generated, the layout is not. The form's state — one field per parameter, a value object of one
value held as that value, one of several values as a group (
f.Price.Amount), a list of rows as rows (f.Wheels[i].Pressure,f.Wheels.Add(new())), aBelongsToas the id a select picks — is an internal type Rask writes beside the entry; what the page shows is markup the page writes. - Different forms, different entries. A short "quick add" and a full create are two
private static Create(…)overloads, each with its form (severalCreates); a form that edits one part is a step of its own (Rename(…),Reprice(…)), whose form isForm.For(Product.Reprice, id). - What the form must not carry is a parameter, or a step before the save. The signed-in user, a parent from the
route:
Create(ProjectId project, string title)takes it as a parameter the page fills (f.Project = ProjectId), never a field the reader edits; or the page calls a step on the aggregate in hand. - Every rule is the aggregate's. As a field is committed, its value object's rules and the entry's dry run — the
attributes,
Rules(),IsUnique("…"),WhenMissing("…")— are asked, each refusal under its field; on submit the entry runs, and a refusal is shown the same way. Nothing is checked twice by different code.
What a form over an entry asks by itself
A form over an entry asks what the entry would ask, with nothing written on the form: each value object as its field is committed, then the entry's dry run — the rules every save asks and the store's own.
public sealed partial record DestinationName(string Value) : Text(Value, MinLength: 2, MaxLength: 255);
public sealed class Destination : Aggregate<DestinationId>, IUpdatable
{
public DestinationName Name { get; private set; }
public static void Configure(EntityTypeBuilder<Destination> b) =>
b.HasIndex(d => new { d.Name, d.TenantId }).IsUnique("A destination with this name already exists.");
}
Form.For(Destination.Create)[f => [
Ui.Input.Bind(() => f.Name), // both rules, no step
Ui.Button.Submit["Save"],
]]
The value object's own rules. A parameter whose value object holds ONE value and is
declared from a base record — Text, Number, Integer, Day or Moment, its base's
arguments and any Rules() of its own, or : Value with ONE positional member (record Rank(int Value) : Value) and
its Rules() — is a field of that value, made through the value object's Create as the field is committed, every
refusal under the field. The control is told what the value object declares (maxlength, min, the input's type)
through its generated __Field, so the form and the constructor cannot drift. A public static Validate on a value
object an aggregate holds is never asked — the build says so (RASK132) rather than let it
look like a rule that passed.
A value object of several values is a group. Range, or record Opening(DateOnly? Date, decimal? Quantity) : Value
with its own Rules(), is one field per member — f.Opening.Date, f.Opening.Quantity — made through its Create
with what the group holds, each Problem under the member it names: Problem.At(Quantity, "Both or neither.") is
under Opening.Quantity as the field is left, not only on save. A member it may not lack is required under its own
path; a nullable one (Opening? opening) left wholly empty is handed over as null, nothing in it required until one
is filled. A Range is one field: Ui.Field.Bind(() => f.Km) draws both ends under one label.
Required follows the parameter's type. No attribute is needed:
- a non-nullable value object (
DestinationName name) is required: a text one is asked about""andTextanswers that it is required, in the reader's language; one over a number or a day says the one sentence below - a
TextdeclaredRequired: falseis not: an empty field is the value"" - a nullable value object (
DestinationName? alias, a one-value struct asNormPercent? discount) is optional: an empty field (text: only blanks) is not put to the rule and is handed over asnull - a non-nullable number, day, enum or id (
int axles,DateOnly built,VehicleId vehicle) is held empty until one is typed — never a0nobody chose — and refused as required when left so; aboolis never empty - a plain
stringis the entry's to refuse — a[Required]on it, or aRefusein the factory — told by the dry run under its field
The one sentence is the strings catalog's ValidationRequired — This field is required., with the kit's built-in
translations — so it follows the reader's language, and a catalog of your own can reword it. A
control bound to a field the form requires says aria-required="true"
(how a control knows). These are not attribute
validation, so RaskValidation.AutoValidate = false does not switch them off.
The entry's dry run. Once every field makes its value, the entry is tried (Destination.DryRunCreate(…), nothing
written) as each field is committed and again on submit, and what it would be refused for is shown under its field —
a Refuse, the validation attributes, the FluentValidation rules and Rules() that
every save asks, and what only the store refuses: a name an IsUnique("…") index finds taken,
an id no row of the tenant's has (WhenMissing). A field typed into is committed as it is left, unless it says
.Live(), .Debounce(…) or .Defer() (bind timing).
The aggregate's unique rules. Write the IsUnique("…") in the aggregate's own Configure: an index declared
in a helper method or an IEntityTypeConfiguration, one without a message, and one on a row inside an aggregate are
enforced by the save and not asked beforehand. The message shows under the field, or under each field of an index
over several:
- over exactly the index's columns: one that names
TenantIdabout the current tenant's rows — the tenant is the one in flight, never the form's to say — and one that does not about every tenant's rows (an index is what you write) - an edit form does not collide with the row it was filled from: its dry run runs over that stored aggregate, as its save does
- the same indexes are asked as by a dry run: an index
filter other than its own columns being
NOT NULLis skipped
It is a courtesy, never the rule: two people can pass it at the same moment, and the save — the index itself, which a
save never pre-queries — still refuses the second, shown the same way. A model you write
by hand (Form.Model(…)) gets none of this — write the rule on the field
(.Validate(…)) and let the save report the index.
Attributes. A field is told what the attributes say — on the parameter of a written Create or step, and on the
property a generated Create or Update made the parameter from:
| Attribute | The form's control | Every save — so the entry and its dry run | The column |
|---|---|---|---|
[Required] |
– (on a plain string, the dry run's refusal) |
checked, on the aggregate's property | NOT NULL (EF Core's) |
[StringLength], [MaxLength], [MinLength], [Length] |
a text input's maxlength/minlength — over a value object, the tighter of the attribute and the value object's own |
checked | [MaxLength]/[StringLength] the length (RASK128 when it and the value object disagree) |
[RegularExpression] |
a text input's pattern when the browser reads the expression the same way |
checked | – |
[EmailAddress], [Phone], [Url] |
the input's type (email, tel, url) |
checked | – |
[Range], [Compare], [AllowedValues], your own ValidationAttribute… |
– | checked | – |
[DataType] |
the input's type: Password, EmailAddress, PhoneNumber, Url; Date on a DateTime or a Moment (a day alone); MultilineText a textarea |
– | – |
[Editable(false)] |
a read-only input, which wires no write | – | – |
[UIHint] |
the kit control Ui.Field.Bind draws where one fits (FieldHints.Switch, FieldHints.RadioGroup, FieldHints.MultilineText) |
– | – |
[Display] |
the label (Name), help text (Description) and placeholder (Prompt) Ui.Field.Bind and a Ui.Field holding a bound control draw — a .Label(…) still wins |
the {0} of its messages, and the name a missing reference is called by |
– |
One name, written once. [Display(Name = "Jármű")] on the parameter — else on the aggregate property of its name,
which the entry writes (VehicleId vehicle → Vehicle) — is copied onto the form's field, so
Ui.Field.Bind(() => f.Vehicle) is labelled "Jármű" with no .Label(…), a DataAnnotations message's {0} says it, an id
that names no row says "Nincs ilyen jármű.", and the read face's column (VehicleId for a BelongsTo<Vehicle>) is
headed by it. A row's member and a value object's member are named by their own [Display] the same way. Rask's own
field messages ("This field is required.", a value object's refusals, a store rule's sentence) name no field: they are
shown under it.
A rule on the aggregate's property is asked by the dry run whether or not the entry's parameter carries it; the
control is told only what the parameter (or, for a generated entry, the property) says. FluentValidation rules — the
aggregate's own static void Rules(InlineValidator<T> rules), or an AbstractValidator<T> — are asked by every save
and so by the dry run, MustAsync included, each under the field of its property's name; a row's controls are told
what is stated for the child (maxlength, min), and NotEmpty(), MaximumLength, PrecisionScale(p, s) give the
column what their attribute twin gives. The value object stays the recommended way: see
three ways to say a rule.
[Editable(false)] keeps the reader from changing the field; it does not stop the aggregate's own method from changing
the property. The read face (ProductRead) carries [Display], [DisplayFormat] and [ScaffoldColumn] from the
aggregate's property — a BelongsTo's onto its key column — so a list's columns are named, written and shown as the property says
(ui-kit — columns from the row's members).
Moving off IHasForm
IHasForm, IHasCreateForm and IHasUpdateForm made a form model of every property an aggregate stored —
ProductModel, Product.Create(model), Product.Update(id, model), Product.Model(id), product.ToModel(). They
make nothing now (RASK207, whose quick-fix takes the trait off and says IUpdatable for an
edit):
| Before | After |
|---|---|
class Product : Aggregate<ProductId>, IHasForm |
class Product : Aggregate<ProductId>, IUpdatable — a Create and an Update generated from what it stores |
private readonly ProductModel _p = new(); Form.Model(_p).OnSubmit(p => Product.Create(p)) |
Form.For(Product.Create) |
_p = await Product.Model(id); Form.Model(_p).OnSubmit(p => Product.Update(id, p)) |
Form.For(Product.Update, id) |
Product.Create(model, p => p.AssignTo(user)) |
a parameter of a written Create(…, UserId owner), or a step before Save() |
partial class ProductModel { public bool Notify { get; set; } } |
a parameter of a written Create(…, bool notify) / Update(…) |
a command carrying ProductModel |
a command carrying what the entry takes, its handler calling the entry |
Test.FormShows(new ProductModel { … }) |
Test.FormShows(new ProductCreateInput { … }) or the entry itself |
What a table carries
Choosing what a table carries
A table carries only what the class says. Each trait is a marker interface beside the base, read like a sentence —
Company : Aggregate<CompanyId>, IBelongsTo<Tenant>, ISoftDeletes, IUpdatable — in any order, with nothing to
implement: the build reads it. An aggregate that says none — Aggregate<Guid> — has no timestamps, no Version, no
entry Update and no generated Delete: its own columns, its read face, its Create, X.Update(id, x => …), and
Find and Save.
| the class says | what the table gets |
|---|---|
IHasTimestamps — or IHasCreatedAt / IHasUpdatedAt for one |
CreatedAt and UpdatedAt, stamped on save |
IVersioned |
a Version concurrency token: a save from a stale copy is refused |
IUpdatable |
the entry X.Update(id, version, …) and X.MayUpdate over its Update — written, or generated when it writes none — and Form.For(X.Update, id) |
IDeletable |
a generated X.Delete(id) that removes the row |
ISoftDeletes |
DeletedAt and a filter; on a root the generated Delete stamps it instead (no IDeletable beside it), on a child its aggregate's removal does — below |
IBelongsTo<Tenant> |
a TenantId in the tenant's key type, a filter, a stamp and a foreign key to the tenant — see Multi-tenancy |
IBelongsToTenantThrough<T> |
no column: the tenant of the T it points at — see Multi-tenancy. One read past the tenant is X.Across("why") (one read across tenants) |
ISharedBy<Tenant> |
no column: one row for every tenant, each reading the rows it uses — a sharing table Rask fills as a tenant's rows name them — see Multi-tenancy |
IInfrastructure |
plumbing beside the domain — a queue, a cache, a session — never counted as a second aggregate |
IBelongsTo<Tenant> names the app's tenant aggregate, the one that says ITenant, and the table keeps the tenant in
that aggregate's key: a Guid? for a Guid (or string) tenant, an int? or a long? for a numbered one, the
typed id for a typed one. With neither IDeletable nor ISoftDeletes there is no Delete at all — calling it is a
compile error, which is what a behaviour-rich aggregate wants.
public sealed class Product : Aggregate<Guid>, IHasTimestamps, IVersioned, IUpdatable, IDeletable { } // what rask new scaffolds
public sealed class Order : Aggregate<Guid>, IHasTimestamps, IVersioned, IUpdatable, ISoftDeletes { } // keep the row when deleted
public sealed class Invoice : Aggregate<Guid>, IHasTimestamps, IVersioned { } // behaviour-rich: no Update, no Delete
public sealed class Reading : Aggregate<Guid>, IHasCreatedAt { } // append-only: no UpdatedAt, no Version
What the table does not carry, the generated types do not either. A Reading like the one above has no
Version, and its read face has CreatedAt and nothing else of the framework's:
Reading.OrderBy(r => r.UpdatedAt) is a compile error, not a query that fails. DeletedAt is on a read face
only for a table that says ISoftDeletes.
A child Entity says only the timestamps and ISoftDeletes — OrderLine : Entity<Guid>, IHasTimestamps,
VirtualTank : Entity<VirtualTankId>, IHasTimestamps, ISoftDeletes. Tenancy, the version, the delete and the
entries are the aggregate's. A trait the class cannot carry is RASK146, an error: an
aggregate's trait on a child, IBelongsTo<T> beside IBelongsToTenantThrough<T>, IDeletable beside
ISoftDeletes, or IBelongsTo<T> of an aggregate other than the one that says ITenant.
History and the one in force
ISoftDeletes on a child keeps a child its aggregate lets go of. Removed from the collection — by Sync,
Remove, a list's own — its row stays, stamped with DeletedAt, together with what it holds: whatever points at it
(a fueling at a virtual tank) still does, and a unique index over it still counts it, so the name it held stays taken.
The aggregate's load and the child's read face no longer see it; IgnoreQueryFilters() lists it again. The same
interface on an aggregate root is its soft delete: the meaning comes from where it stands.
One in force keeps the history of a child and at most one of it in force — a return's filings, a period's
closings. The child says when one is, in its own Configure, and the aggregate that holds it says nothing; it puts
the next one in force and ends the last in one step:
public sealed class Period : Aggregate<PeriodId>, IVersioned
{
private readonly List<PeriodFiling> _filings = [];
public IReadOnlyList<PeriodFiling> Filings => _filings;
public void Close(Filer by) => _filings.Put(PeriodFiling.Of(by, Clock.Now), end: f => f.Unfile(by, Clock.Now));
public void Reopen(Filer by) => _filings.End(f => f.Unfile(by, Clock.Now));
public bool Closed => Filings.InForce() is not null;
}
public sealed class PeriodFiling : Entity<PeriodFilingId>
{
public DateTime? UnfiledAt { get; private set; }
static void Configure(EntityTypeBuilder<PeriodFiling> b) => b.InForceWhile(f => f.UnfiledAt == null, Texts.AlreadyFiled);
}
The rule is a unique index on the child's key to the aggregate whose collection holds it, over the rows in force only
— filtered on SQL Server, partial on PostgreSQL and SQLite — so of two saves that each file one, one commits and the
other is refused with a RaskValidationException under the new child's row (Filings[1].PeriodId) carrying the
message; never a check-then-insert. InForce(), Put(…) and End(…) ask the same condition in memory, and
InForce() throws if it ever finds two.
Announcing a save
A save refreshes the screen of the session that made it — IDataChanges, at no cost — and every other page whose live
query reads what it wrote: the save is announced to the process once it commits, while a page is reading that aggregate,
and to nothing otherwise. Nothing is declared on the aggregate or in the component; see
live queries. IBroadcasts, which once had to say it, is retired
(RASK208).
- After the commit, never on a rollback — the same rule the interceptors already follow.
- It needs no session. A background job's write announces itself too.
- Who may see it: nobody new — the refetch is the page's own query, under its own rules (tenant, permissions).
Like every subscription in Rask today, it reaches the process it was published in. Behind a load balancer, a page on the other server catches up on its next refetch.
Why a type argument and not an attribute. The base is part of the type, so the generator reads it at compile time and can never quietly miss it, and a trait in the wrong place is a compile error at the declaration. Nothing is reflected over at run time, so a trimmed publish has the same shape as a debug build.
The traits are the whole family. Anything per-property or expression-shaped — a column name, an index, a value
converter, a length — stays in static Configure, which is where
it can actually be expressed.
Why the scaffold checks the version and soft-deletes nothing
Both are opt-in, and rask new says IVersioned and IDeletable. They look symmetrical and are not.
Soft delete used to be the default and is not any more, because it costs an ordinary application more than the
recovery is worth. A stamped row still occupies its UNIQUE constraints, so deleting the account a@b.com and
letting that person sign up again fails on a row nobody can see. "Delete my account" has to be able to mean
delete. And Rask already ships real recovery — SQLite snapshots and Litestream — so keeping the
row was solving that problem a second time, worse, while charging every query a predicate.
The version check is scaffolded because a lost delete is visible and a lost update is not. A deleted row is
gone and somebody notices; two people editing one form both see "Saved" and the second silently erases the
first. The cost that would normally argue for turning it off — an unhandled concurrency exception — Rask already
absorbs: a stale save is a RaskValidationException about the whole form, which the form shows at its top.
An entity that knows its own time
CreatedAt and UpdatedAt — on a table that says IHasTimestamps — are normally the framework's, stamped by
Rask's auditing interceptor on save. An
entity in a package that does not own the DbContext cannot rely on that, and a column nobody stamped
reads as 0001-01-01 — which is not obviously wrong anywhere it is used. Rask's own file store found this the
hard way: an unstamped CreatedAt became a Last-Modified header and the cutoff of an orphan sweep.
So Entity<TId> has a protected void Stamp(DateTime at), and the interceptor fills only what is still
unset. An entity that knows its own creation time says so; one that does not gets the framework's; neither can
end up at 0001-01-01.
The transaction boundary
One aggregate, one transaction. An operation's entry, Save() and every generated write load one aggregate
whole, change it and save it in one transaction — its children, its version check and its events with it. That is
the boundary the aggregate was drawn for — so app code does not write an aggregate on a DbContext of its own
(db.Products.Add(p), db.Update(order), db.Remove(supply), then SaveChangesAsync()), which goes around the
factory, the operations, their roles and the save's rules; RASK133 points at it, outside seeds,
migrations and tests. A change that seems to need two aggregates is decided in this order:
Draw the boundary again. Two things that must always change together are usually one aggregate: a part that never stands on its own is a child, not an aggregate of its own.
Follow from an event. The first aggregate raises what happened, and a handler runs the second one's operation after the commit — through the outbox by default, at least once and in its own transaction (
static Task On(E e);[Immediate]in memory for what can be lost):public sealed record OrderPlaced(OrderId Order, StockItemId Stock, Quantity Quantity) : IEvent; public sealed partial class Order : Aggregate<OrderId>, IVersioned { public StockItemId Stock { get; private set; } public Quantity Quantity { get; private set; } public void Confirm() => Raise(new OrderPlaced(Id, Stock, Quantity)); // what happened, said once } public sealed partial class StockItem : Aggregate<StockItemId>, IVersioned { public void Reserve(Quantity quantity) { /* its own rules */ } static Task On(OrderPlaced e) => StockItem.Reserve(e.Stock, e.Quantity); // a durable handler, on the aggregate it changes }The handler is one line on the aggregate it changes (
On(E)): it decides nothing, it calls the operation that does. A refusal there is the second aggregate's to give, and the outbox retries the handler, so the operation it calls should be safe to run twice.The last resort: both in one save. A check that must hold across two aggregates at the very moment of the write — and that no boundary and no event can carry — saves them together, below. It is the exception, so each use says why:
manyAggregates: "…".
Changing two aggregates together — the last resort
When neither a new boundary nor an event will do, the two entries run inside one Db.Transaction, and each joins it:
OrderId order = await Db.Transaction(async () =>
{
await StockItem.Reserve(stock, quantity); // its rules, its version check — refused rolls both back
return await Order.Place(reference, stock, quantity); // joins the same transaction
}, manyAggregates: "A reservation that followed from an event could sell the last unit twice");
Each entry still loads its own aggregate whole and asks its own rules; what changes is that both commit together or
neither does, and the events of both are published after that one commit. The reason is written where the decision
is made, so the next reader does not have to guess which invariant needed it — and a transaction that writes a
second aggregate without one is refused in a test (below). An
operation that always needs it says so once, in its Configure: b.Operation(x => x.M, manyAggregates: "why").
Every write the block makes joins it, with no parameter to pass: a factory's or an operation's entry, a set write
(X.UpdateWhere(…), X.DeleteWhere(…)) and a SaveChangesAsync() on the app's own context alike — one connection,
one transaction, at the block's isolation. An entry's id is there for the rows added after it, a later read in the
block sees what it wrote, and the stamps, the Version bump, LockedBy and DeletionRules() apply as they do
outside. The one context that stays out is one whose connection its owner opened by hand
(db.Database.OpenConnectionAsync()) — it runs as it always did — so open none inside a block.
One aggregate per transaction: manyAggregates:
An aggregate is the transaction boundary. A Db.Transaction that writes a second one is a decision, so it says
why, where it is made:
await Db.Transaction(async () =>
{
await filling.Save();
foreach (var withdrawal in withdrawals) await withdrawal.Save();
}, manyAggregates: "A filling and its withdrawals are only valid together");
builder.Services.AddRaskData(o => o.OneAggregatePerTransaction = AggregatePolicy.Throw); // Off | Warn | Throw
What a second aggregate without a reason meets is
RaskDataOptions.OneAggregatePerTransaction:Warnby default (a warning in the log naming the aggregates, once per transaction),Throw— aManyAggregatesExceptionnaming them (Supply 42, Tank 7), the transaction rolled back — orOff. ATestDatabaseruns atThrow, so a test finds the transaction that owes a reason; a test's ownservices:can set it back.What counts is what the transaction's saves wrote, each aggregate once: a child counts as its aggregate (a changed
SupplyPartis itsSupply), the same aggregate saved twice is one, and two rows of one type are two. Rask's own tables — outbox, jobs, mail, sessions, passkeys, stored files, cache, push subscribers — are no aggregate of the app's and never count; an app table of the same kind saysIInfrastructureon its class. A set write (X.UpdateWhere,X.DeleteWhere) counts once, asPairing (set), whatever rows it touched; a batch ofX.UpdateEachorX.Importstates its own reason — each row is an aggregate of its own — and is let through. A rawExecuteUpdateand aBulkInsertare not saves and are not counted (RASK187 points at the first). A save refused for another reason counts nothing.Nested blocks are one transaction. The outermost counts, and a nested
Db.Transaction(…, manyAggregates: …)states the reason for all of it.The build says it first. RASK178 points at a
Db.Transactionwhose work writes two aggregate types with nomanyAggregates:, and its quick-fix writesmanyAggregates: "TODO: why"for you to fill in.A test asks it outright:
Db.Record()records every transaction that commits in the flow until disposed —saves.Transactionsholds each one's aggregates and reason — andsaves.EachWroteOneAggregate()fails on one that wrote more, reason or not:using var saves = Db.Record(); await DeliveryNote.Write(note, 0); saves.EachWroteOneAggregate();
After the commit: AfterCommitFailures
What a Db.Transaction announces runs once it has committed: its [Immediate] handlers and components, the data-changed notice
to the live pages, the outbox's wake-up. The work has happened by then, so a step that throws there does not make the
call fail:
builder.Services.AddRaskData(o => o.AfterCommitFailures = AfterCommitFailure.Throw); // Log (default) | Throw
Log(the default): the error is logged, every step after it still runs, and the caller sees the committed work succeed — which it did.Throw: every step still runs, then the caller gets the failure — the exception itself, or anAggregateExceptionwhen several threw. The work is committed all the same.- A durable handler is not such a step: it runs from the outbox, retried until it succeeds.
Update(id, apply), Delete and Save() also take db:, to stage their change on a context the caller already
holds and saves itself — a seed, a context of the app's own — rather than open one: await Order.Update(orderId, o => o.Confirm(), db: db), then db.SaveChangesAsync(). One SaveChangesAsync is one transaction, so writes staged on one
context commit together, and the concurrency check is made at that save. An entry — Create(…), an operation's —
takes no db:: inside Db.Transaction it joins the transaction instead.
Declared projections: Projects
Some state is made from rows rather than kept on them: a fueling's sequence number per pistol, the company a vehicle last fuelled for. Written as a save hook — an interceptor that looks at what changed and writes elsewhere after the save — it runs outside the save's transaction, so a crash between the two leaves them disagreeing, and it hangs on whichever aggregate happened to be saved. Declare it on the rows instead, and let the rows raise an event:
public static void Configure(EntityTypeBuilder<Fueling> b) =>
b.Projects(f => new { f.Moment, f.PistolId, f.Number },
changed => new FuelingsToNumber(changed.Values(f => f.PistolId)));
- What it watches: a save that adds a
Fueling, removes one, or changes a memberwatchednames to another value —f => f.Moment, or several asf => new { … }. A change to anything else, or a member set to the value it held, raises nothing. Anything but the row's own members (f => f.Number + 1) is refused where it is declared. - Once per save:
raisegets every row the save changed asProjectedRows<Fueling>— each aProjectedRowwithBefore(a detached copy of what is stored,nullfor an added row) andAfter(the row as written,nullfor a removed one).changed.Values(f => f.PistolId)is every value a member holds on either side, each once: the pistol a fueling left as well as the one it went to. Returnnullto raise nothing for this save. - Raised as the aggregate's own event, onto the first row the save changed: a durable handler of it —
static Task On(FuelingsToNumber e)— has its outbox row written in that same save, so the projection's work is stored with the change or not at all; an[Immediate]handler hears it after the commit, and a rollback raises nothing. A retried save raises it once, and araisethat throws fails the save. - On an aggregate, since its events ride on its rows: a
Projectson a child or a plain entity is refused where it is declared. Declaring the same event again on the same type replaces the first declaration. - Nothing is written to the database for it — no column, no SQL, no migration.
A check and the writes it guards: Db.Transaction
A read face (Pistol.Count, Tank.Any) opens a context of its own, so a check made with one outside the write runs
outside the save it guards, and two requests can both see "free" and both take it. A check like that belongs in the
operation itself — its Rules(…) or a Refuse reading the read face runs in the entry's transaction. Where the check
and the write must still be put together by hand, Db.Transaction holds them — Laravel's DB::transaction, Rails'
transaction(isolation:):
await Db.Transaction(async () =>
{
if (await Pistol.Count(p => ids.Contains(p.Id)) != ids.Count) return; // runs in the same transaction
await Tank.Update(id, t => t.Change(...)); // joins it, with no db:
}); // provider default isolation
await Db.Transaction(async () => { ... }, isolation: IsolationLevel.Serializable);
var order = await Db.Transaction(async () => await Order.Create(reference)); // hands back a value
Everything without a
db:joins.Find,Where,Any,Count, the read faces,Create,Update,Delete,Save, child writes and the unique/store-rule checks each still open a context — on the transaction's connection, enlisted in it.A
db:you pass joins too, or is refused — it never commits on its own beside the work. On the same connection string, and not opened before it was handed in, it is enlisted (sodb.SaveChangesAsync()writes inside the transaction); on another database, in a transaction of its own, or with its connection already open, the call throwsInvalidOperationException. The same goes fordb.BulkInsert(...). It stays yours: when the transaction ends — committed, rolled back or retried — it is out of it and back on its own connection, so the samedbcan go into the nextDb.Transactionor save on its own.Your own context joins at its first command. A context of the app's own — from the factory
AddRaskData<T>(o => …)registers or any whose options carry Rask's interceptors (AddInterceptors(sp.GetServices<ISaveChangesInterceptor>()), which aRaskAppand every documented hand-wired host already add) — is enlisted before the first thing it runs inside the block, even when it was created before it: a LINQ read,SaveChangesAsync, any command it sends. So its save does not wait on the locks the transaction's own reads took, a rollback takes its writes back, and a laterdb: dbcall finds it joined. It is handed back on its own connection like anydb:. Nodb.Database.BeginTransactionAsync()inside the block — the context is already in one, and Rask refuses a second with anInvalidOperationExceptionsaying so;Database.Migrate()andEnsureCreated()are refused the same way, since schema work belongs outside the block (at startup).A context on another database, already in a transaction of its own, or whose connection you opened before the block runs as it always did, outside — and a
db:call with it is refused as above. A context that joins as it opens still has the open reported to its connection interceptors, on the transaction's connection. Rask's SQL Server and SQLite interceptors send nothing then — that connection got itsSETs and pragmas when it opened. AConnectionOpenedinterceptor of your own that sets a connection up should skip it the same way:if (eventData.Context?.Database.CurrentTransaction is not null) return;.A job or a mail queued inside is a row in the transaction.
Jobs.Enqueue(...)(with or without.UnlessWaiting()) andMail.Send(...)write on its connection: no processor sees them before the commit, and a rollback leaves nothing to run or deliver. Their table must be in the same database; otherwise the enqueue throws rather than write outside.Committed when the work completes; rolled back when it throws, and the exception reaches you unchanged.
After the commit, never before: domain events are published, the outbox is woken (its rows were written inside, so they commit or roll back with the work), and the session's queries are told what changed. A rollback announces nothing.
What Rask starts while the block is open runs outside it. A render that a
StateHasChangedasks for, a handler's repaint between its awaits, a query's fetch and a subscription's stream each read on a connection of their own, at the database's default isolation, and see only what is committed. They never take the transaction's locks, so a page's read cannot deadlock the work it repaints for. Reads that the block's own code makes are inside the transaction.isolationis optional. Omitted, none is sent and the database's default applies: read committed on SQL Server and PostgreSQL. SQLite is serializable and has one writer — a secondDb.Transactionwaits at itsBEGINfor the first to commit, then sees what it wrote.Serializable is what makes a check-then-write safe on SQL Server and PostgreSQL. Two such transactions that both read the same rows and then write cannot both commit: SQL Server picks a deadlock victim (1205), PostgreSQL refuses one with a serialization failure (40001). Both are transient, so with retrying on (the default for both providers) the loser runs again from the top and sees the winner's row; with retrying off it throws.
On a retrying context the whole work may run again, so keep side effects outside the database (an HTTP call, a cache write) out of it — or put them in a durable handler.
Mail.SendandJobs.Enqueueare rows, so they are written once. What an attempt that rolled back did to the aggregates it saved is taken back — their remembered read,Version, domain events, and a key the database generated for a row that is gone — so an aggregate loaded or made before the block is saved by the retry as if the failed attempt had never run.Nested
Db.Transactionjoins the outer one. Same connection, same transaction, committed by the outermost. It is not a savepoint, and asking for a differentisolationinside throws.One connection, one thing at a time: no
Task.WhenAllover reads inside it — RASK142 says so where it sees one.What does not join: the cache does not take part —
Cache.RememberandCache.Forgetact at once and are not undone by a rollback. Nor does a context built without Rask's interceptors and never handed to a Rask call.
It works the same from a live event handler, an HTTP endpoint, a job and a test, on a RaskApp host and on
one wired by hand with AddRaskData<TContext>().
Testing a model
An operation's rule is asked of the aggregate itself — found, and its method called, with nothing saved — and
Test.Refuses says which field the refusal names:
[Fact]
public async Task An_unpaid_order_does_not_ship()
{
await using var database = await TestDatabase.Start<AppDbContext>();
var order = (await Order.Find(await Order.Place(OrderReference.Create("PO-1"))))!;
Test.Refuses(() => order.Ship(TrackingNumber.Create("1Z999"))).Whole();
}
Every test gets a real database in one line — SQLite in memory, a database of the test's own, made from the app's own context so the save runs exactly what it runs in production: the domain's rules, the interceptors, the version check, the domain events:
[Fact]
public async Task A_second_supply_of_one_delivery_note_is_refused()
{
await using var database = await TestDatabase.Start<AppDbContext>();
await Supply.Register(company, details, parts);
(await Test.Refuses(() => Supply.Register(company, details, parts))).At("Details.Number");
}
[Fact]
public async Task Two_edits_from_one_version_keep_one()
{
await using var database = await TestDatabase.Start<AppDbContext>();
var id = await Supply.Register(company, details, parts);
var version = (await Supply.Find(id))!.Version; // both forms were filled from the same version
(await Test.Concurrently(
() => Supply.Update(id, version, details, partsA),
() => Supply.Update(id, version, details, partsB))).Whole(); // one kept, the other refused as stale
}
TestDatabase.Start<AppDbContext>()— orTestDatabase.Start()for an app on Rask's own context — is a named shared-cache SQLite database in memory, kept alive for the test and let go when it is disposed. A database started inside a test binds the read faces and the entries for that test's own flow, so tests run in parallel, each on its own rows. The schema is made once per model and copied into each later database, so a start costs well under a millisecond.- The same answers as production. It is configured through
UseRaskSqlite, so text compares as the app's app's language says, a decimal orders as a number,end - startis a duration andDb.Lockholds — what the app writes is neutral (code written for one database), and Rask's own conformance suite proves each of those behaves the same on SQLite, SQL Server and PostgreSQL (the conformance suite). An app's tests need no SQL Server of their own. Events.Fake()records what a save published;Test.Concurrentlyproves exactly one of two writers wins — a version check, a unique index, aLockRead.ForUpdatelock or aDb.Lock.
A test makes its data as the app does — through the aggregate's generated entries, the values written out (testing).
Testing the domain has all of it — fixtures shared by a class, what a save runs, the fake clock, a signed-in user.