Relatude.DB.CMS
1.1.1.6-alpha
See the version list below for details.
dotnet add package Relatude.DB.CMS --version 1.1.1.6-alpha
NuGet\Install-Package Relatude.DB.CMS -Version 1.1.1.6-alpha
<PackageReference Include="Relatude.DB.CMS" Version="1.1.1.6-alpha" />
<PackageVersion Include="Relatude.DB.CMS" Version="1.1.1.6-alpha" />
<PackageReference Include="Relatude.DB.CMS" />
paket add Relatude.DB.CMS --version 1.1.1.6-alpha
#r "nuget: Relatude.DB.CMS, 1.1.1.6-alpha"
#:package Relatude.DB.CMS@1.1.1.6-alpha
#addin nuget:?package=Relatude.DB.CMS&version=1.1.1.6-alpha&prerelease
#tool nuget:?package=Relatude.DB.CMS&version=1.1.1.6-alpha&prerelease
Relatude.CMS
A .NET 8 content backend layered on Relatude.DB, an in-process object-oriented graph database (NuGet Relatude.DB.Server). You model your domain as C# interfaces (the engine generates the implementing classes), declare relationships as small marker classes, and read/write through a NodeStore. Provides the base content model (IItem, IPage, ISite, ITemplate), pluggable content rendering (MVC, Razor Pages or any IResult), and DB access plumbing.
Using an AI coding agent? This package ships a Claude Code skill (
relatude-cms) with the same guidance below. The commerce layer is documented inRelatude.Ecom(relatude-ecomskill), which builds on this one.
Host setup (Program.cs)
Relatude.DB runs in-process inside an ASP.NET Core app:
var builder = WebApplication.CreateBuilder(args);
builder.AddRelatudeCMS() // Relatude.DB, CMS settings, analytics and content routing
.AddMvcRendering() // MVC views and controllers; AddRazorPagesRendering() adds Razor Pages
.AddRendering(o => o.RenderRazorView<IArticle>()); // code defaults: what renders a type without a template
builder.AddRelatudeDB(o => o.OnDatamodelInit = (dm, _) => dm.AddCmsContentModel()); // optional, before or after: one ServerOptions
var app = builder.Build();
app.UseRelatudeCMS(); // starts the engine (admin UI at /relatude.db) and the analytics middleware
app.MapRelatudeCMS(); // content URLs to what renders them, see Content rendering
app.Run();
The schema (datamodel) is managed through the admin UI at /relatude.db, where you point a datamodel source at the assembly/types holding your model interfaces, or registered in code: builder.AddRelatudeDB(o => o.OnDatamodelInit = (dm, _) => dm.AddCmsContentModel()).
Getting a NodeStore
NodeStore (namespace Relatude.DB.Nodes) is the entire data API. In a request, inject RelatudeCmsContext (Relatude.DB.CMS.Web, scoped): .Db is the store as the visitor (the signed-in user's read access, the request's culture, published content only), .Admin the store as the master admin for trusted code, and beside them User, UserId, CultureCode, Url, Node, Content, Render and GetUrl(node). Code with no request injects IRelatudeDBAccessor (Relatude.CMS.Engine) and uses .Database, or reads RelatudeDBRuntime.Database where there is no DI. Authentication is the host's; the CMS reads the signed-in user's node id from the NameIdentifier claim (which CmsPrincipal.For(user, scheme) writes), else finds the user by the Email claim, and a page the visitor may not read redirects to login, or answers 403 once signed in (AddRelatudeCMS(o => o.LoginRedirect = false) turns that off). Convention: methods that touch data take NodeStore db as a parameter rather than capturing it.
Modeling: interfaces, not classes
An entity is an interface extending IItem (and usually IPage for routable content):
public interface IPage : IItem {
string MetaTitle { get; set; }
string MetaDescription { get; set; }
Reference<ITemplate> Template { get; set; } // the page's template, or none
}
IItem gives every node Guid Id, string Name, NodeMeta Meta (Meta.Address is the URL slug). IPage adds SEO metadata and a Template reference. Other base types: ISite, ITemplate and its kinds (see Content rendering), ITree, ICountry, ICMSUser, ICmsUserGroup.
Relations are declared as classes deriving from OneToMany<,>, ManyToMany<,>, OneToOne<,>, OneOne<>, or ManyMany<>, with nested marker classes naming each end:
public class PageTree : OneToMany<ISitePage, ISitePage> {
public class Parent : One { } // exposed on ISitePage as PageTree.Parent Parent
public class Children : Many { } // exposed on ISitePage as PageTree.Children Children
}
OneToMany<TOne,TMany> exposes One/Many; ManyToMany<TFrom,TTo> exposes ManyFrom/ManyTo; OneToOne<,> exposes OneFrom/OneTo. Attributes (Relatude.DB.Nodes) tune mapping: [Node(...)] on the interface, [Exclude], and per-type property attributes ([StringProperty], [IntegerProperty(Indexed=true, UniqueValues=true)], [DecimalProperty], [GuidProperty], …). Embedded value maps use [EmbeddedMapProperty(KeyProperty = ...)].
Navigating relations on a loaded node
Relation ends are objects, not plain collections:
if (page.Parent.IsSet()) { … } // One: has value? / Many: Count() > 0
var parent = page.Parent.Get(); // One → T (throws if not set; guard first)
page.Parent.TryGet(out var parent); // safe variant
foreach (var child in node.Children.Get()) // Many → IEnumerable<T>
In queries prefer Include(...) over lazy .Get() to avoid N+1.
CRUD through NodeStore
var page = db.Create<IPage>(); // in-memory, NOT yet persisted
db.Insert(page); // or CreateAndInsert<IPage>(p => { ... })
db.Update(existing); // UpdateOrFail / UpdateIfExists / Upsert / ForceUpsert
db.Delete(node); // also Delete(Guid id) / Delete(IEnumerable<Guid>)
var p = db.Get<IPage>(id); // throws if missing
db.TryGet<IPage>(id, out var page2); // safe
bool exists = db.Exists<IPage>(id);
Relations are set/cleared as their own operations (property-selector lambda):
db.SetRelation(page, p => p.Template, templateId); // one-end: replaces
db.AddRelation(template, t => t.Pages, page); // add to many-end
db.RemoveRelation(template, t => t.Pages, page); // remove one link
db.ClearAndSetRelation(node, x => x.Many, newSet); // replace whole set
Write methods accept flushToDisk (default false) and have …Async counterparts. Mutating a property on a loaded node still requires an Update call to persist.
Querying
db.Query<T>() returns IQueryOfNodes<T,T> — fluent and expression-based; nothing runs until a terminal call:
var results = db.Query<IPage>()
.Where(p => p.MetaTitle != null)
.Include(p => p.Template) // eager-load; ThenInclude to go deeper
.OrderBy(p => p.Name)
.Page(0, 20) // pageIndex0based, pageSize (or Take/Skip)
.Execute(); // ResultSet<IPage>; .ToList()/.ToArray() also
var one = db.Query<IPage>().Where(p => p.Meta.Address == slug).FirstOrDefault();
long n = db.Query<IPage>().Count();
Also: WhereSearch/Search (BM25 + optional semantic/vector), WhereRelates/WhereNotRelates/WhereRelatesAny, WhereIn, WhereTypes, Facets(), Sum(...), SelectId(), a string-based Where("a => …") overload, and db.TryParseUrl(url, out var keys) for URL → node through the store's URL manager (what content rendering uses; db.TryGetFromAddress<T>(address, out var node) is a raw address lookup that bypasses the manager). Query context controls culture/visibility/revisions: db.Context.Culture("nb-NO").Hidden().Admin().Create(). Default queries exclude hidden nodes.
Transaction plugins (triggers)
Cross-cutting node behavior goes in a plugin. Derive NodeTransactionPlugin<T>, override OnBeforeNodeAction / lifecycle hooks, register with db.RegisterTransactionPlugin(...). Example: Relatude.Ecom's ShopTemplateSetterPlugin : NodeTransactionPlugin<IProduct> sets each product's address on upsert with transaction.UpdateAddress(key, RelatudeUrlHelper.ToUrlSlug(name)). Switch on the NodeOperation enum (Upsert, Insert*, Update*, ForceUpsert, Delete*).
Content rendering (Relatude.DB.CMS.Web.Rendering)
Rendering a URL takes three steps:
- Resolve.
ContentResolverfinds the node the URL addresses through the store's URL manager (db.TryParseUrl), so base paths, domains, parent-chain URLs and cultures route the way the manager builds them. The result is aContentMatch: the node, its template or its type's code default, and the culture the URL matched.ContentResolvertakes the URL apart once per request, and a file URL is served by the same routes:MapRelatudeCMS()answers files and adjusted files (resized images, converted video) through Relatude.DB'sFileHandler, range requests included, read as the visitor, so read access applies to files too. OverrideContentResolver.Resolveto find content another way, such as preview links, and callMatch(node)to give the node its template or code default. - Select. The first answer wins: selectors added with
o.Select(...), in order; for a page with a template, the template's kind; for content without one, the code default for its type, then, witho.ViewPerType(), the view named after its type. - Dispatch. The adapter for the target's rendering system serves it:
| Target | Adapter | Rendered by |
|---|---|---|
RazorViewTarget(view) |
AddMvcRendering() |
RelatudeContentController, with the node as the view's model |
MvcControllerTarget(controller, action, area) |
AddMvcRendering() |
the host's controller action |
RazorPageTarget(page, area) |
AddRazorPagesRendering() |
the Razor Page |
ResultTarget((http, match) => IResult) |
always mapped | any IResult: Blazor SSR's RazorComponentResult, JSON, a template engine |
Templates. IPage.Template is a Reference<ITemplate>. A template's kind is its node type:
| Kind | Renders with |
|---|---|
ITemplate |
only a selector, o.Select(...) |
IRazorViewTemplate |
RazorViewTarget(ViewName) |
IMvcControllerTemplate |
MvcControllerTarget(Controller, Action), a blank action meaning Index |
IRazorPageTemplate |
RazorPageTarget(PagePath) |
NodeTypes lists the node type ids the template is for, their subtypes included; an empty list means every type, as the last choice. The CMS pins its type ids with [Node(Id = …)]; pin a site's own types too, since an unpinned id comes from the full name.
builder.AddRelatudeDB(options => options.OnDatamodelInit = (dm, _) => {
dm.AddCmsContentModel(); // IItem, IPage, ITemplate and the template kinds
dm.AddNamespace<IArticle>(); // the site's own node types
});
builder.AddRelatudeCMS() // after AddRelatudeDB
.AddMvcRendering().AddRazorPagesRendering() // MVC + Razor Pages
.AddRendering(o => o
.Select((http, m) => http.Request.Query["view"] == "print" ? new RazorViewTarget("Print") : null)
.Select((http, m) => m.Content is IArticle { Body.Length: > 20_000 } ? new RazorViewTarget("ArticleLong") : null)
.RenderRazorView<IHomePage>("Home") // code defaults, for content without a template
.RenderRazorView<IProduct>(p => p.InStock ? "Product" : "SoldOut")
.RenderMvcController<ISection>("Section")
.RenderRazorPage<ILandingPage>("Landing")
.RenderRazorView<IPage>("Default") // any other page
.TemplateKind<IJsonTemplate>(t => new ResultTarget((http, m) => Results.Json(new { m.Content.Name }))));
var app = builder.Build();
app.UseRelatudeDB();
app.UseRelatudeCMS();
app.UseStaticFiles();
app.UseRouting(); // after the static files, so a file request never looks for content
app.MapRelatudeCMS(); // pattern "{**url}" by default
- Code defaults say what renders content of a type and its subtypes that has no template, with no template in the database:
RenderRazorView<T>(view)(no name: the type's name without its leadingI, soIArticlegivesArticle),RenderRazorView<T>(node => view),RenderMvcController<T>(controller, action),RenderRazorPage<T>(page)(with or without the leading/),RenderResult<T>((http, node) => IResult), andRender<T>(target)/Render<T>(node => target)for anything else. They work for anyIItem. Defining a type again replaces it; a per-node default returningnullleaves the content unrendered.o.ViewPerType(), off by default, renders whatever is left with the view named after its type. - Templates render by their kind, and a page without a template gets the closest one by type. Templates and code defaults compete by distance from the page's type: the type itself, else its nearest base type. A template as close as a code default wins over it, so editors can take over a type with a template that lists it; a template listing no types is the last choice, after every code default. Two equally close templates are ambiguous, which is the usual case for layout variants (
articleandarticle-wideboth forIArticle), so pages of such a type choose their template; two equally close code defaults (a type deriving from two interfaces) are ambiguous too, settled by a default for the type itself. - Checks. A page whose template is not for its type throws on request, as does content of a type with equally close code defaults, and so do an ambiguous page without a template and a plain template no selector rendered. Saving such pages is refused (on update;
CreateAndInsertinserts empty first), through plugins a Relatude.DBIStoreInitializerservice registers on every store, whatever order the setup calls come in. A check logged when the store opens, and after templates change, reports views, controller actions and Razor Pages that code defaults name but that do not exist, code defaults for types not in the datamodel, ambiguous types, the names in templates, plain templates when no selector is added, and unknown node types. A default decided per node is not checked up front. - Full control. Selectors decide before everything, templates included; to override one template, test
m.Template(itsNameorId) in a selector.o.TemplateKind<T>(t => ...)adds a kind of the host's own, asked before the built-in ones.AddMvcRendering()andAddRazorPagesRendering()add the rendering systems a site uses;AddRendering(o => ...)holds the code defaults, selectors and kinds, and every call adds to the same options. - Reading the content. Bind it as a parameter,
public IActionResult Index([FromContent] IArticle article)(aContentMatchparameter gets the whole match, includingTemplateByTypeandTypeDefault), or callHttpContext.GetContent<IArticle>()/GetContentMatch()from anywhere. Resolution and selection run once per request, lazily, whoever asks first.[FromContent]skips validation, which would read every related node. - Rendering is optional. Without
MapRelatudeCMS()nothing is routed, andGetContent<T>()still works. - Explicit routes win. The content routes are catch-alls, so every explicit route of the host beats content at the same path. A URL with no content, or a page with nothing to render it, falls through to the host's
MapFallbackor a 404. - Controllers must be conventionally routed. No
[Route], no[ApiController]: dynamic routes cannot reach attribute-routed actions. - Outbound URLs come from the store.
db.GetUrl(page)goes through the same URL manager. - Composing with another router, such as a legacy CMS: call
ContentResolver.GetRender(http)andMvcContentRouteTransformer.TrySetRouteValues(target, values)from your own transformer.
Website2 in the repository is a complete example: a page tree with articles and products, code defaults for every page type, two article templates editors choose between, selectors, and a menu built from the tree.
RelatudeUrlHelper.ToUrlSlug(name) (Relatude.CMS.Engine.Web) makes a URL slug from a name (lower case, æ/ø/å and diacritics transliterated). The store makes it unique when it is saved as an address.
The full manual is docs/manual.md in the repository (rendered as docs/manual.html).
CMS settings and analytics (Relatude.CMS.Settings, Relatude.DB.CMS.Web.Analytics)
builder.AddRelatudeCMS() registers the CMS's own settings, CmsSettings, as a Relatude.DB custom settings set: a CMS tab beside each database's settings in the admin UI, read from code as db.Settings.Get<CmsSettings>(). It is layered like every custom setting: relatude.settings/cms.json (SHARED), the admin UI's saves (THIS SERVER), then RelatudeDB:CustomSettings:cms in appsettings. Its first group is Analytics; more CMS settings go in the same class.
builder.AddRelatudeDB();
builder.AddRelatudeCMS();
var app = builder.Build();
app.UseRelatudeDB();
app.UseRelatudeCMS(); // analytics: after UseRelatudeDB, before the site's pages and static files
Analytics is off until turned on (CMS > Analytics > Record page views). Then:
- Every page view is recorded in the custom log
cms-pageviews("Page views" under Logs in the admin UI, with graphs from its statistics): path, host, referrer host, visitor hash, visitor type (human,bot,unknown), bot name, country, region, city, position, browser, operating system, device, language and duration. A page view is a GET answered 200 with HTML. The admin UI,/-info/, the paths inExcludedPathsand prefetches are never page views. - The log is the database's once it is made. It is created when it is missing - the first time analytics is on, and again if it is deleted in the admin UI. After that, changes made in the admin UI (retention, columns taken out, statistics, switches) are kept. The code only adds columns: each column in
PageViewLogcarries theDefinitionVersionthat introduced it, and the database's storage remembers the version its log has (cms/pageviews-log.json). When the CMS is newer, the columns added since are put into the log if missing, once; a column removed afterwards stays removed. A log made before this file existed counts as version 1. To add a column, give it the next version and raiseDefinitionVersion. - Nothing happens while the visitor waits. The middleware only queues the page view (
PageViewQueue).AnalyticsWorker, a hosted service, waitsLookupDelaySeconds(5) for the browser's bot check to report, looks the visitors of a batch up at once withdb.Services.IPLookup(once per address and user agent; settled verdicts are kept for 10 minutes), and records the entries. A failed lookup records the page views without it and warns once per 10 minutes. - The bot check is added to every HTML page just before its last
</body>, as the CMS'sHtmlRewriterfinds it (InjectBotCheck,InlineBotCheck). Only an uncompressed UTF-8 HTML 200 of at most 16 MB is held to do it; everything else streams through untouched. CallUseResponseCompression()beforeUseRelatudeCMS(), if at all. - No cookie and no address are kept (GDPR). The visitor is the daily visitor hash,
SHA-256(IP + User-Agent + Language + daily salt)(DailyVisitorHash). The salt is 32 random bytes per UTC day, held in memory only and never written, so a hash cannot be traced back or linked across days. A process restart starts a new salt, so a visitor seen on both sides of it counts twice that day. The referrer is only its host, and the query string is left out unlessLogQueryStringis on. IAnalyticsHostis the database side (settings, custom logs, the database's storage, IP lookups, reserved paths). The default isRelatudeAnalyticsHost, the default database's; tests replace it.- Behind a proxy, call
app.UseForwardedHeaders()first, so the address hashed and looked up is the visitor's.
Donations (Relatude.CMS.Models.Donations)
A generic donation node model with the list/detail projection behind the WAF.Client Donations admin module (postWebAPI(session, "Donations", "List" | "Get", …)). The model namespace holds only the IDonation interface — a datamodel source scans it, so anything else in that namespace would be registered as a node type. The wire DTOs (DonationRow/DonationListResult/DonationDetail) and the pure DonationAdminProjection live in Relatude.CMS.Models.Donations.Admin. Sites extend the model with their own node interface (public interface IMyDonation : IDonation { … }) — a member may be declared in only one interface of the hierarchy.
Both namespaces are registered as datamodel sources — matching is exact, and an unregistered base interface silently drops all inherited fields from the derived type:
"DatamodelSources": [
{ "Id": "<unique guid>", "Name": "My site", "Namespace": "MySite.Models", "Type": "AssemblyNameReference", "Reference": null },
{ "Id": "<unique guid>", "Name": "Donations", "Namespace": "Relatude.CMS.Models.Donations", "Type": "AssemblyNameReference", "Reference": "Relatude.DB.CMS" }
]
The admin controller stays in the host — it derives from the host framework's admin API base (e.g. WAF's BaseAdminAPIController), which this package does not reference. Routed as wafapi/Donations/{action}, the shape is:
[HttpPost]
public DonationListResult List(int pageSize = 25, int pageIndex = 0, string? sortBy = null, bool sortDesc = true,
string? categories = null, string? statuses = null, string? paymentMethods = null, string? search = null) {
_ = Context.Session; // WAF's admin gate — throws (→ 403) without a session
var query = _cx.Database.Query<IMyDonation>() // WhereIn(d => d.Status/…) for non-empty filters
.OrderBy(DonationAdminProjection.SortExpression<IMyDonation>(sortBy), sortDesc);
var page = query.Page(pageIndex, pageSize).Execute();
return new DonationListResult { Rows = page.Values.Select(d => DonationAdminProjection.ToRow(d)).ToList(), TotalCount = page.TotalCount };
}
Get(id) is TryGet<IMyDonation> → DonationAdminProjection.ToDetail(d, formGuid: …), where the host resolves the originating form's content guid from IDonation.FormId (see DonationDetail.FormGuid — the admin client cannot query by ContentId). The host also snapshots the form's name onto IDonation.FormName when the donation is created — denormalized on purpose, since the list sorts and searches it server-side (AQL orders node properties, not values computed at projection time); a later rename therefore does not retro-rename existing donations. Category (onetime/recurring/business) and free-text search have no AQL form — when active, materialise the ordered set, filter with MatchesCategory/MatchesSearch, then page.
Notes
Create<T>()does not persist — follow withInsert/CreateAndInsert; callUpdateafter mutating a loaded node.- Relation ends aren't
Lists — use.Get()/.IsSet()/.TryGet(). - Relation changes go through
SetRelation/AddRelation/RemoveRelation, not property assignment. - This is a library with no entry point; engine start and schema live in the host app and the
/relatude.dbadmin UI. - Relatude.DB source/API reference: https://github.com/Relatude/Relatude.DB
- Donations: every
DatamodelSourcesentry needs its own uniqueId— the store refuses to boot without one. - Donations: the enum-like string values (
PaymentMethod,Status,GiftType,Frequency) are matched case-sensitively by the admin module's filters — store exactly the values documented onIDonation(all lowercase, e.g.vippsrecurring).
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Relatude.DB.Server (>= 1.1.1.6-alpha)
NuGet packages (4)
Showing the top 4 NuGet packages that depend on Relatude.DB.CMS:
| Package | Downloads |
|---|---|
|
Relatude.Core
Relatude .Net 10.0 Headless CMS and E-commerce solution |
|
|
Relatude.DB.Ecom
Relatude E-commerce backend API for Relatude.DB. Builds on the Relatude.CMS package. |
|
|
Relatude.DB.MCP
An MCP server for Relatude CMS: AI agents read and change a site's datamodel, content and templates at runtime, with the rights of the user their key is for. |
|
|
Relatude.DB.Scriban
Scriban templates for Relatude CMS: page templates, emails and any other text, kept in the database or as files, evaluated at runtime. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 1.1.11.42-alpha | 0 | 11/24/2026 |
| 1.1.11.35-alpha | 63 | 11/22/2026 |
| 1.1.10.34-alpha | 55 | 11/22/2026 |
| 1.1.10.32-alpha | 48 | 11/22/2026 |
| 1.1.9.30-alpha | 65 | 11/20/2026 |
| 1.1.8.29-alpha | 75 | 11/18/2026 |
| 1.1.8.28-alpha | 90 | 11/17/2026 |
| 1.1.7.25-alpha | 100 | 11/16/2026 |
| 1.1.6.25-alpha | 175 | 11/13/2026 |
| 1.1.2.21-alpha | 133 | 11/9/2026 |
| 1.1.2.20-alpha | 98 | 11/9/2026 |
| 1.1.2.14-alpha | 194 | 11/5/2026 |
| 1.1.1.13-alpha | 176 | 11/2/2026 |
| 1.1.1.12-alpha | 111 | 11/1/2026 |
| 1.1.1.9-alpha | 106 | 10/30/2026 |
| 1.1.1.8-alpha | 109 | 10/29/2026 |
| 1.1.1.7-alpha | 139 | 10/23/2026 |
| 1.1.1.6-alpha | 103 | 10/21/2026 |
| 1.1.1.3-alpha | 188 | 10/17/2026 |
| 1.0.43 | 275 | 10/5/2026 |