Rask.Data 0.24.1-alpha.0.1283

This is a prerelease version of Rask.Data.
There is a newer prerelease version of this package available.
See the version list below for details.
dotnet add package Rask.Data --version 0.24.1-alpha.0.1283
                    
NuGet\Install-Package Rask.Data -Version 0.24.1-alpha.0.1283
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Rask.Data" Version="0.24.1-alpha.0.1283" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Rask.Data" Version="0.24.1-alpha.0.1283" />
                    
Directory.Packages.props
<PackageReference Include="Rask.Data" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Rask.Data --version 0.24.1-alpha.0.1283
                    
#r "nuget: Rask.Data, 0.24.1-alpha.0.1283"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Rask.Data@0.24.1-alpha.0.1283
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Rask.Data&version=0.24.1-alpha.0.1283&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=Rask.Data&version=0.24.1-alpha.0.1283&prerelease
                    
Install as a Cake Tool

Rask.Data

A data layer for Entity Framework Core apps with one goal: you declare aggregates, and that is all. No DbContext class, no DbSet property, no IEntityTypeConfiguration, no registration, and no IDbContextFactory injected to read a row or save a form. Underneath it is ordinary EF Core, and anything richer than a create, an update or a delete is EF Core exactly as you know it.

  • Aggregate<TId> and Entity<TId>: domain-driven design's building blocks as base classes. An entity carries Id; an aggregate adds domain events. Everything else is a trait the class says, an interface beside the base read like a sentence, in any order — Aggregate<Guid>, IHasTimestamps, IVersioned, IUpdatable, IDeletable is the CRUD shape rask new scaffolds: IHasTimestamps (or IHasCreatedAt / IHasUpdatedAt), IVersioned, IUpdatable, IDeletable or ISoftDeletes, IBelongsTo<Tenant>. A bare Aggregate<Guid> has none of them. A source generator finds every one and builds the model, so nothing is scanned or reflected and a trimmed publish cannot quietly drop a table.
  • Value objects that compare by value: a record, a record struct, or a class on ValueObject an entity holds maps as an EF complex type, columns on the owner's row. Strongly-typed ids get a generated value converter with nothing declared; mapping rules live in a plain public static void Configure(EntityTypeBuilder<T>) on the type.
  • Queries off the type, rows from a generated read face: Product.Where(...), Product.Count(), Product.Search(text), Product.AsQueryable() return ProductRead rows — its columns and value objects, as the aggregate holds them, plus the joins its ids imply. C# 14 static extension members, so an aggregate that compiles today has them. Every read is untracked and opens and disposes its own context, which is what makes them safe on a page that lives as long as a browser's socket. AsQueryable() is a standard IQueryable<T> that opens a context per execution: hand it to a data grid and it sorts and pages in the database.
  • A generated Create and Update: an aggregate that writes no factory gets Product.Create(…) (and Product.New(…)), one parameter per stored property, and an IUpdatable one with no Update gets Product.Update(id, version, …). A form is over an entry — Form.For(Product.Create), Form.For(Product.Update, id) — its fields the entry's parameters, the edit form filled from the stored aggregate, every rule the aggregate's asked as a field is left.
  • Writes off the type: Product.Create(…), Product.Update(id, version, …), Product.Update(id, p => …), each operation's entry by its name, Product.New(…) then product.Save(), and Product.Delete(id, version), which removes the row under IDeletable (or stamps DeletedAt under ISoftDeletes; with neither there is no delete at all). The id is never a form's field; a stale Version is refused (IVersioned). Each takes an optional DbContext to join a caller's transaction.
  • Find, change, Save: var order = await Order.Find(id); loads the aggregate whole (a filtered query by key, so a soft-deleted row is null), order.Ship(…) runs its rule, await order.Save() writes only what changed, syncs its children by id and refuses a stale Version. Save() on a new aggregate inserts it.
  • State stays inside: a public setter or mutable field on an aggregate, entity or value object is a build error with a lightbulb fix (RASK084), and an entity exposing a mutable collection of entities is a warning (RASK085).
  • TestDatabase.Start<AppDbContext>: a real database for a test in one line, through the app's own context, so behaviour on an aggregate is tested against the database, model and SaveChangesAsync it ships on rather than a mocked DbContext. With nothing to configure (and Rask.SQLite.EntityFrameworkCore referenced) it is a SQLite database in memory of the test's own, shared by every context it hands out, and tests run side by side. A save runs the app's whole interceptor chain — domain events reach their handlers after the commit, the outbox stores a durable handler's event — as it does in production. TestDatabase.FromEnvironment<AppDbContext>("APP_TEST_DB", (o, cs) => o.UseSqlServer(cs)) takes the real database server from an environment variable — a database per test, or a shared standing one taken in turns — and skips the test where the variable is unset.
  • Three ISaveChangesInterceptors: auditing timestamps and versions, opt-in soft delete (for an aggregate that says ISoftDeletes, a delete becomes a DeletedAt stamp behind a global query filter), and after-commit domain-event publication through Rask.Cqrs.
  • Current and multi-tenancy: Current.UserId, Current.Principal, Current.Claim(type) and Current.IsInRole(role) answer from a static factory or anywhere else with no constructor to inject into, and Current.Tenant / Current.User are your own tenant and user rows once those aggregates say ITenant / IUser — read ahead, held, never a query. IBelongsTo<Tenant> on the class gives a table a TenantId and a query filter no read can compose away, and an entity under it is read through its root; the tenant comes from the signed-in user.
  • BulkInsert: the bulk insert EF Core leaves out (ExecuteUpdate/ExecuteDelete exist; inserts are out of its scope). Batched, with the change tracker cleared as it goes so memory stays flat.

Use

public sealed class Product : Aggregate<Guid>, IHasTimestamps, IVersioned, IUpdatable, IDeletable
{
    [Required, MaxLength(200)]
    public string Name { get; private set; } = "";
    public Money Price { get; private set; } = new(0m, "EUR");
}   // no factory, no Update: both generated from what it stores

public sealed record Money(decimal Amount, string Currency);

// read: no context in scope, nothing left open, nothing tracked
var products = await Product.OrderBy(p => p.Name);

// a list page: the filter only when typed, the order the address names, one page and the total, a total under it
var page = await Product.When(search, (q, s) => q.Where(p => p.Name.Contains(s)))
    .OrderBy(p => p.Name, SortDirection.Of(dir)).Page(number, 15);      // RowPage: Rows, Total, Number, Size
var stock = await Product.Sum(p => p.Stock);

// write: off the type too — or Form.For(Product.Create) / Form.For(Product.Update, id) on a page
var product = await Product.Create("Anvil", new Money(9.90m, "EUR"));
await Product.Update(id, version, "Anvil", new Money(8m, "EUR"));   // at the version read: only changed columns; a stale one throws
await Product.Delete(id, version);                                   // removes the row

// a domain method: load the aggregate, run it, save it
var order = await Order.Find(orderId);
order!.Cancel(DateTime.UtcNow);
await order.Save();                            // only changed columns, children synced, stale Version throws

// anything richer: plain EF Core, one context, one transaction (the writes above join it with db: db)
await using var db = await contexts.CreateDbContextAsync(ct);
var order = await db.Set<Order>().FirstAsync(o => o.Id == orderId, ct);
order.Cancel(DateTime.UtcNow);
await db.SaveChangesAsync(ct);

In a Rask app that is the whole of it — the host builds the model and points the model surface at it. Elsewhere, name the context once and hand it over after the container is built:

builder.Services.AddRaskCqrs();
builder.Services.AddRaskData<AppDbContext>();
builder.Services.AddDbContextFactory<AppDbContext>((sp, o) => o
    .UseSqlite("Data Source=app.db")
    .AddInterceptors(sp.GetServices<ISaveChangesInterceptor>()));

var app = builder.Build();
Db.Configure(app.Services);

In a WebAssembly app AddRaskData<AppDbContext>() is the whole of it: the package's browser build points the model surface at the context itself, and — with AddRaskQuery() — a save refreshes the page's Rask.Query queries about what it wrote, as it does in a Rask server session.

A class that does not derive from Entity<TId> stays an ordinary EF Core entity: write your own context and configurations and use them exactly as before. Registering an IDbContextFactory<YourContext> is the whole of opting out at the app level.

A delete, db.Remove(product), removes the row — or, for an aggregate that names ISoftDeletes, stamps DeletedAt so the row drops out of queries (IgnoreQueryFilters() brings it back); a save of an IVersioned aggregate against a stale Version throws DbUpdateConcurrencyException; and any IEvent raised on the aggregate is published after the change commits.

To load many rows at once — seeding, an import, a migration — await db.BulkInsert(products) (or db.Products.BulkInsert(...)) saves them in batches, clearing the change tracker between each so memory stays flat. The interceptors above still run for every row. Each batch commits on its own so a long import does not hold SQLite's only write lock end to end; o.SingleTransaction = true makes it all-or-nothing.

For the fastest load, o.SkipChangeTracking = true writes the rows with one prepared INSERT and no entity entries at all. It is opt-in because it runs no ISaveChangesInterceptor — the writer stamps the audit columns itself, but entities carrying domain events are rejected rather than silently losing them, and anything it cannot map faithfully throws and names the reason.

Non-overlapping ranges

A chip held by a driver, a room booked by the hour: two rows with the same key must not cover the same moment. A UNIQUE index only stops identical rows, so declare the rule on the model instead:

b.NoOverlap(x => new { x.TenantId, x.Code }, x => x.Period, "A chip is held by one driver at a time.")
 .Where(x => x.DriverId != null);
b.NoOverlap(x => x.RoomId, x => x.StartsAt, x => x.EndsAt, "The room is booked then.");

Ranges are half-open ([from, to)), a null end is open, a null key part and an empty range conflict with nothing. PostgreSQL holds it as an exclusion constraint, SQL Server and SQLite as triggers — all written by the migrations of UseRaskPostgres, UseRaskSqlServer and UseRaskSqlite — and a violating save is refused with the rule's message under the range's field, as an IsUnique("…") duplicate is. On a provider that writes no such DDL the rule would be silently ignored, so AddRaskData<TContext>() refuses to boot instead.

Declare which text is searchable, and search it from LINQ — ranked, word-aware, diacritic-insensitive:

modelBuilder.Entity<Post>().HasFullTextSearch(p => new { p.Title, p.Body });

var hits = await Post.Search(query).Where(p => p.Published).Take(20);
var marked = await Post.Search(query).Select(p => FullText.Snippet(p.Body));

Search(text) works on a read face, on a ModelQuery and on any EF Core IQueryable; it returns best matches first and keeps composing. Typed text is always words, never query syntax. The index arrives through a migration and the database keeps it current:

  • SQLite — UseRaskSqlite(...) from Rask.SQLite.EntityFrameworkCore, or a plain UseSqlite plus UseRaskFullTextSearch(): an FTS5 index kept current by triggers; adding it to an existing table fills it.
  • In the browser — Rask.SQLite.Browser's UseSqlite(BrowserSqlite.ConnectionString("app")) plus the same UseRaskFullTextSearch(): the same FTS5 index in the WebAssembly app's local database.
  • PostgreSQL — UseRaskPostgres(...) from Rask.Postgres: a stored generated tsvector column with a GIN index, no triggers.

On SQL Server, or a plain UseSqlite without UseRaskFullTextSearch(), AddRaskData<TContext>() refuses to boot a context that declares an index.

A value inside a JSON column gets its own index the same way: HasJsonIndex(o => o.Meta.Status) adds an expression index spelled exactly as EF Core writes the filter, so the filter is an index search. SQLite only for now, and refused at boot elsewhere. See the full-text search guide.

Part of the Rask framework. MIT licensed.

Product Compatible and additional computed target framework versions.
.NET net11.0 is compatible.  net11.0-browser1.0 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (11)

Showing the top 5 NuGet packages that depend on Rask.Data:

Package Downloads
Rask.Server

The ASP.NET host for Rask, a full-stack .NET web framework, with every battery: database (SQLite or SQL Server, and PostgreSQL with the Rask.Postgres package, picked by Rask:Database:Provider), mediator and query cache, accounts, background jobs, transactional email, cache, file storage, outbox, operator dashboard, durable logs, Web Push, SQLite snapshots and continuous backup. Renders Rask components with live updates over a WebSocket. RaskApp.Create(args).Run<App>() is the whole Program.cs, and RaskApp.Create(args).Serve() the whole server of a WebAssembly client; app.Configure(c => c.Jobs.Off()) is how an app does without one. Depends on Rask, the shared core.

Rask.WebPush

Server-side Web Push for Rask: the browsers that subscribed, kept on the app's own database, and a send that reaches them — Push.Send(message) for everyone, .To(userId) for one person's devices — dropping subscriptions the push service says are gone. Signs VAPID (RFC 8292) and encrypts (RFC 8291 aes128gcm) with in-box System.Security.Cryptography, and maps the subscribe endpoints a WebAssembly client or SPA posts to. Push.Fake() for tests.

Rask.Mail

Durable transactional email for a Rask app, queued on its own database — no broker, no Redis. Compose an email (a Rask component rendered to HTML is the body), call `Mail.Send(email)`, and a background `MailProcessor` delivers it over SMTP (MailKit) — at-least-once, with exponential-backoff retries and dead-lettering, as the tenant it was queued for. Zero-config in development: logs or writes `.eml` files when no SMTP server is set. Server-side; pairs with EF Core.

Rask.Outbox

A transactional outbox for .NET on your app's own database (no broker, no Redis): give a domain-event handler `IDurableHandler<T>` and its row is written to an `OutboxMessage` table in the **same transaction** as the change that raised the event, so it is never lost and never fires for a rolled-back change. A background `OutboxProcessor` then runs each handler at-least-once with retries, woken by the save itself. Plain `IEventHandler<T>`s keep running in memory; each handler chooses. Server-side; pairs with Rask.Data and Rask.Cqrs.

Rask.Jobs

Durable background jobs for a Rask app, stored in its own database — no broker, no Redis. Enqueue a job (an `IJob`, dispatched to its Rask.Cqrs `ICommandHandler`) with `Jobs.Enqueue` and a background `JobProcessor` polls the table and runs it — at-least-once, with exponential-backoff retries. Supports delayed (run-at) jobs and durable interval-recurring jobs. A source generator registers each job type for reflection-free lookup. Server-side; pairs with Rask.Cqrs and EF Core.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.24.1-alpha.0.1328 0 12/2/2026
0.24.1-alpha.0.1313 0 12/2/2026
0.24.1-alpha.0.1301 0 12/2/2026
0.24.1-alpha.0.1283 0 12/2/2026
0.24.1-alpha.0.1270 0 12/1/2026
0.24.1-alpha.0.1269 0 12/1/2026
0.24.1-alpha.0.1266 53 12/1/2026
0.24.1-alpha.0.1226 55 12/1/2026
0.24.1-alpha.0.1215 55 12/1/2026
0.24.1-alpha.0.1214 58 12/1/2026
0.24.1-alpha.0.1196 62 12/1/2026
0.24.1-alpha.0.1195 64 12/1/2026
0.24.1-alpha.0.1188 63 12/1/2026
0.24.1-alpha.0.1187 64 12/1/2026
0.24.1-alpha.0.1152 79 11/30/2026
0.24.1-alpha.0.1147 85 11/30/2026
0.24.1-alpha.0.1145 85 11/30/2026
0.24.1-alpha.0.1139 95 11/30/2026
0.24.1-alpha.0.1120 87 11/30/2026
0.24.0 251 11/16/2026
Loading failed