Document DB
A lightweight, database-agnostic document store for .NET that turns your database into a schema-free JSON document database with LINQ querying, spatial/geo queries, vector / ANN search, and full AOT/trimming support. Store entire object graphs — nested objects, child collections — as JSON documents. No CREATE TABLE, no ALTER TABLE, no JOINs, no migrations. One API, multiple database providers.
Features
Section titled “Features”- Multi-provider — SQLite, SQLCipher (encrypted SQLite), LiteDB, IndexedDB (Blazor WASM), DuckDB, PostgreSQL, CockroachDB, SQL Server, MySQL, MariaDB, Oracle, CosmosDB, MongoDB, Amazon DocumentDB, Azure Table Storage, Amazon DynamoDB, Redis, RavenDB, and Google Firestore with a single API. Provider reference
- Zero schema, zero migrations — store objects as JSON documents
- Fluent query builder —
store.Query<User>().Where(u => u.Age > 30).OrderBy(u => u.Name).Paginate(0, 20).ToList()with full LINQ expression support for nested properties,Any(),Count(), string methods, null checks, and captured variables IAsyncEnumerable<T>streaming — yield results one-at-a-time with.ToAsyncEnumerable()- Expression-based JSON indexes — up to 30x faster queries on indexed properties
- SQL-level projections — project into DTOs via
.Select()at the database level - Aggregates — scalar
.Max(),.Min(),.Sum(),.Average()as terminal methods; aggregate projections with automatic GROUP BY viaSql.*markers; collection-level Sum, Min, Max, Average on child collections - Grouped aggregation —
Query<Order>().GroupBy(o => o.Status).Having(g => g.Count() > 5).Select(g => new { g.Key, Revenue = g.Sum(o => o.Total) })with multi-part and derived keys, plus a string form (GroupBy("customer.tier")). Pushed down to real SQLGROUP BY/HAVINGon the relational providers and evaluated client-side on MongoDB, Cosmos, LiteDB, and IndexedDB. Learn more - Ordering —
.OrderBy(u => u.Age)and.OrderByDescending(u => u.Name)on the fluent query builder - Pagination —
.Paginate(offset, take)translates to SQLLIMIT/OFFSET - Table-per-type mapping —
MapTypeToTable<T>()gives a document type its own dedicated table. Unmapped types share a configurable default table - Custom Id properties —
MapTypeToTable<T>("table", x => x.MyProp)to combine with a dedicated table, orMapIdProperty<T>(x => x.MyProp)to override the Id while keeping the type in the default shared table - Document diffing —
GetDiffcompares a modified object against the stored document and returns an RFC 6902JsonPatchDocument<T>with deep nested-object diffing - Surgical field updates —
SetPropertyupdates a single JSON field without deserialization.RemovePropertystrips a field. Both support nested paths - JSON Merge Patch (Upsert) —
Upsertuses RFC 7396json_patchto deep-merge a partial object into an existing document, preserving unset nullable fields. Inserts if the document doesn’t exist - Merge-vs-replace flags — pick the write mode explicitly without switching methods:
Update(doc, patch: true)deep-merges instead of full-replacing, andUpsert(doc, patchIfUpdate: false)replaces the body wholesale instead of merging. The same flags apply on a JSON collection (Collection(type).Update(jsonObject, patch: true)), which is the precise way to do partial updates. Relational providers; non-default modes throwNotSupportedExceptionon the document-native and key-partitioned stores. Learn more - Bulk operations —
Query<T>().Where(...).ExecuteUpdate(x => x.Prop, value)and.ExecuteDelete()issue a single SQL statement against all matching documents — no deserialization, no client-side loop - Typed Id lookups —
Get,Remove,SetProperty, andRemovePropertyaccept the Id asobjectso you can pass aGuid,int,long, orstringdirectly. Unsupported types throwArgumentException - JSON collections — read and write documents as raw JSON through one API, addressed either by name (schema-free — no CLR type at all) or by CLR type (late-bound — a registered type, but no instance):
store.Collection("orders")/store.Collection(typeof(Order)). Both giveInsert/Update/Upsert/Get/Remove/Clearplus a fluent string-grammarQuery()returningJsonObjects. A type-keyed collection stores the body AS-IS but rides the full write pipeline (tenancy, temporal, versioning/CAS, spatial + vector sidecars, interceptors, change notifications) and resolves paths through the type’s metadata; a name-keyed one has no registrations at all and infers field types from the query (with an explicittotal:numberhint where nothing else pins them). Ideal for generic HTTP intake, message-bus payloads, ETL, gateways, and genuinely schema-free data. Relational providers. Learn more - Typed
DocumentContext— an optional, EF-Core-style typed front-end overIDocumentStore. Declare aggregates on apartialcontext with[Document(typeof(User), Id = nameof(User.Email), JsonContext = typeof(AppJsonContext))]and a bundled source generator emits aDocumentSet<T>per type plus DI sugar (AddAppContext(...)scoped,AddAppContextFactory(...)for the MAUI/Blazor/desktop story). Work model-first —await db.Users.Where(u => u.Age >= 18).ToList()— withJsonTypeInfo<T>threaded automatically. Ships in core, works over all providers. Learn more - Computed properties — map a value derived from other fields (
Total = Quantity * UnitPrice, a normalizedlower(Email)) that you filter, sort, and project by exactly like a stored property, though it’s never written into the JSON.MapComputedProperty<T>(o => o.Total, o => o.Quantity * o.UnitPrice)runs in alias mode by default (SQL-inlined, zero schema); passindexed: trueon a relational provider to materialize it as a native generated/computed column + index. Recomputed and written back onto the object on read. Fully AOT/trim-safe. Learn more - Full AOT/trimming support — all
JsonTypeInfo<T>parameters are optional and auto-resolve from a configuredJsonSerializerContext. SetUseReflectionFallback = falseto catch missing registrations with clear exceptions - Optimistic concurrency —
MapVersionProperty<T>(x => x.RowVersion)enables automatic version checking on update/upsert. Version is set to 1 on insert, checked and incremented on update. ThrowsConcurrencyExceptionon conflict. Works across all providers — stored in the JSON blob with zero schema changes - Unit of work —
store.OpenSession()+SaveChanges()with automatic commit/rollback - Batch writes —
BatchInsertinserts a collection in a single transaction with prepared command reuse, auto-generates IDs, and rolls back atomically on failure.BatchUpsert,BatchUpdate, andBatchRemove<T>(ids)apply many writes as one set operation (a single multi-rowINSERT … ON CONFLICTdeep-merge on SQLite/DuckDB, oneBulkWrite/DeleteManyon MongoDB, parallel request waves on Cosmos, a singleDELETE … IN (…)on relational). All-or-nothing — the first version conflict rolls the whole batch back - Spatial / geo queries (full OGC geometry) — beyond point-only
WithinRadius/WithinBoundingBox/NearestNeighbors, a fullGeometrymodel (GeoLineString,GeoPolygonwith holes, multi-geometries) maps viaMapSpatialProperty<T>(x => x.Area)and queries with the topological predicate family —GeoIntersects,GeoContains,GeoWithin,GeoCovers,GeoWithinDistance, and friends — returningSpatialResult<T>withDistanceMeters. Compose spatial predicates inside ordinary LINQ withDocumentFunctions.Intersects/Distance/…(server-side, combinable with otherWhere/OrderBy/paging) and in the string-expression surface too. Backed by a real 2-D spatial index on every SQL provider — SQLite R*Tree, PostgreSQL GiST, MySQLSPATIAL, DuckDB R-Tree, SQL Server spatial index, OracleSDO_GEOMETRY+ MDSYS — plus nativeST_*on CosmosDB and2dsphereon MongoDB. Learn more - Vector / ANN search — register an embedding property with
MapVectorProperty<T>(d => d.Embedding, dimensions: 1536, metric: VectorDistance.Cosine, indexKind: VectorIndexKind.Hnsw)and query withQuery<T>().Where(...).NearestVectors(query, k). Provider-native indexes: pgvector (PostgreSQL),VECTOR+ DiskANN (SQL Server 2025), nativeVECTOR+ HNSW/IVF (Oracle 23ai), embedding policy (CosmosDB),$vectorSearch(MongoDB Atlas),vssextension (DuckDB),sqlite-vec(SQLite). PlusAutoEmbedOnInsert<T>to plug inMicrosoft.Extensions.AI.IEmbeddingGeneratorand embed text automatically on every write. Learn more - Full-text search (all providers) —
MapFullTextProperty<T>(a => a.Body)(or an array of paths) +store.FullTextSearch<T>("orleans persistence")for relevance-ranked search, returningFullTextResult<T>(Document+ normalizedScore) ordered by relevance, with an optional pre-filter and a fluentstore.Query<T>().Where(...).FullTextMatch("...")form. The native index is auto-created and engine-maintained: FTS5 (SQLite),tsvector+GIN (PostgreSQL),FULLTEXT(MySQL), Oracle Text, SQL Server Full-Text, theftsextension (DuckDB), full-text policy (CosmosDB),$text(MongoDB), and an in-memory TF-IDF fallback on LiteDB / IndexedDB. A type must be mapped before it can be searched. Learn more - Composite JSON indexes —
CreateIndexAsync(ctx.User, u => u.Country, u => u.Age)builds a single B-tree across multiple JSON paths on SQLite, SQLCipher, PostgreSQL, MySQL, Oracle, DuckDB, and SQL Server. Learn more - Hot backup —
Backupcopies the database to a file. Available onSqliteDocumentStore,SqlCipherDocumentStore, andLiteDbDocumentStore - Streaming bulk export / import / restore — the
IDocumentBackupstore capability moves a whole store’s contents in and out as a portable, streamed v1 backup:ExportAsync(Stream),RestoreAsync(Stream), and the lower-levelBulkImportAsync(IAsyncEnumerable<RawDocument>). Bodies bound verbatim (no<T>, no reflection — AOT-friendly);BulkWriteModepicks Insert/Replace/Merge/SkipExisting, with a native bulk-copy fast path (10-100× faster) on PostgreSQLCOPY, SQL ServerSqlBulkCopy, and DuckDB appender. Every SQL provider plus MongoDB and Cosmos. Learn more - Clear the whole store —
((IDocumentMaintenance)store).ClearAll()wipes every document type plus temporal-history, spatial, and vector sidecars (test/dev resets) without touching the system catalogs. Implemented on the relationalDocumentStore(SQLite, SQL Server, PostgreSQL, MySQL, DuckDB, Oracle), MongoDB, and CosmosDB; the olderSqliteDocumentStore.ClearAllAsync()delegates to it - Database seeding — register
IDocumentSeeders to populate initial data once at startup. Schema-free seeding is just idempotent writes, so seeders are provider-agnostic; run-once is versioned via aDocumentSeedMarker(bumpVersionto re-run). Wire withAddDocumentSeeder<T>()/AddDocumentSeeder(name, version, delegate)at host startup, or callDocumentSeedRunner.RunAsync(store, seeders)directly (e.g. on MAUI) - SQLCipher encryption — separate
Shiny.DocumentDb.Sqlite.SqlCipherpackage with AES-256 encryption, password-aware backup, andRekeyAsyncto change the encryption key - Multi-tenancy — two isolation strategies: shared-table (single database with automatic
TenantIdcolumn filtering) and tenant-per-database (separate database per tenant via lazy factory). Both resolve the current tenant via a user-implementedITenantResolver. Consumer code is unchanged — tenant isolation is applied transparently - Change monitoring — consume an
IAsyncEnumerable<DocumentChange<T>>of insert/update/remove/clear events withawait foreach (var c in store.NotifyOnChange<User>(ct)). Filter to a single document withWhenDocumentChanged<T>(id)or to the result set of a fluent query withquery.NotifyOnChange(). Buffered in a session and emitted on commit. Learn more - Native change feeds —
IChangeFeedDocumentStore.SubscribeChanges<T>observes all writers via the database’s own mechanism: PostgreSQLLISTEN/NOTIFYtriggers, SQL Server Change Tracking (optionally withSqlDependencyquery notifications), and Cosmos DB native Change Feed. Provisioning is automatic and idempotent - Temporal history (system-time versioning) —
MapTemporal<T>(o => { o.Retention = ...; o.MaxVersions = ...; o.CaptureActor = ...; })opts a type into append-only versioning. Every Insert/Update/Upsert/Remove/SetProperty/RemoveProperty/BatchInsert records a snapshot to a per-type history sidecar. Read it back withHistory<T>(id),AsOf<T>(id, when),Restore<T>(id, version),GetDiffBetween<T>(id, from, to), plus fleet-wideAsOfAll<T>(when),ChangesByActor<T>(actor), andChangesBetween<T>(from, to)— on theITemporalDocumentStorecapability interface, notIDocumentStore. Opt-in per type, on every provider (relational and document/NoSQL). Learn more - Write interceptors — observe and mutate writes as they happen, per-document (
IDocumentInterceptor—Insert,BatchInsertper item,Update,Upsert,Remove) or set-based (IDocumentBulkInterceptor—ExecuteUpdate,ExecuteDelete,Clear). The after-hook runs inside the same transaction, after the write succeeds and before commit, so it sees the generated id/version and can do transactional side effects like an outbox. A before-hook can alsoctx.Cancel()to replace the write entirely. Every provider. Learn more - Soft delete —
opts.AddSoftDelete<Customer>(x => x.IsDeleted)andRemove,ExecuteDelete, andClearall set the flag instead of deleting, while every read hides the flagged documents (IncludeDeleted()opts back in). Nothing is wired into the stores — it’s a global query filter plus a write-cancelling interceptor, the same two public building blocks you’d use to write your own variant. Learn more - Blobs — attach binary payloads (a PDF, an image, a signature) to a document via
DocumentBlob/DocumentBlobCollection, stored in a sidecar table and loaded on demand. The body keeps only metadata (size, content type, file name), so ordinary reads, queries, the change feed, and temporal history never drag the bytes along — unlike a rawbyte[], which base64-inflates theDatacolumn ~33% and materializes on every read. Learn more - Reference geo data —
Shiny.DocumentDb.Geoships an embedded dataset of US states, Canadian provinces, and US & Canadian cities that seeds straight into any store: point-in-region lookups, nearest-city queries, and population data without wiring up an external gazetteer. Plain documents through the normal seeding + spatial machinery, so it’s provider-agnostic. Learn more - Global query filters — register an
AddQueryFilter<T>(u => !u.IsDeleted)predicate that’s automatically AND-applied to every query ofT, plusGet/Update/Remove/SetProperty/RemoveProperty/Clear/ExecuteUpdate/ExecuteDeleteand per-query change monitoring. Mirrors Entity Framework Core’sHasQueryFilter, including named filters,IgnoreQueryFilters()/IgnoreQueryFilters("name"), and captured-variable semantics. Learn more - AI tool integration —
Shiny.DocumentDb.Extensions.AIexposes document types asMicrosoft.Extensions.AItool functions for LLM agents. Per-type capability flags (ReadOnly,All), structured filter expressions, field visibility control, and page size caps. Learn more - Orleans persistence —
Shiny.DocumentDb.Orleansprovides a full Microsoft Orleans stack — grain storage, reminders, cluster membership, and grain directory — on any DocumentDb backend (relational, MongoDB, or Cosmos) through oneIDocumentStoreabstraction. Because grain state is persisted as structured, queryable JSON, you can query grain state directly without activating grains (reporting, dashboards, ops tooling) and get a free audit trail of every mutation viaMapTemporal<T>. Learn more - Telemetry & diagnostics — embedded and always-on: every store emits OpenTelemetry-native metrics (
db.client.operation.durationand friends, plus adb.client.unit_of_work.operationshistogram) andActivitySourcetrace spans per operation — CRUD, fluent-query terminals, temporal, and aunit_of_workparent span per session. Built onSystem.Diagnostics; zero-cost when nobody is listening — subscribe with.AddSource/.AddMeter("Shiny.DocumentDb"). Learn more - JSON Schema validation —
Shiny.DocumentDb.JsonSchemaattaches a JSON Schema (draft 2020-12) to a document type and validates the exact JSON about to be persisted just before the write.options.MapJsonSchema<Customer>(schemaJson)needs no DI (works with a hand-builtnew DocumentStore(options)); a failure throwsDocumentSchemaValidationExceptionwith field-level errors and rolls the write back. Enforces what the C# type can’t —maxLength, ranges,pattern,enum,format. Learn more - OData query endpoints —
Shiny.DocumentDb.OData+Shiny.DocumentDb.AspNetCore.ODataexpose a document type as an OData v4 entity set:$filter/$orderby/$top/$skip/$count/$selecttranslate onto the fluent query and run against any provider. Global query filters always apply underneath, and per-entity-setODataQueryPolicygovernance locks down public endpoints. Learn more - Offline-first sync —
Shiny.DocumentDb.AppDataSyncmakes the store the local cache of an offline-first app that bidirectionally syncs to an HTTP backend viaShiny.Data.Sync.SyncDocumentStore(sync => sync.Sync<TodoItem>())turns an ordinary document type into a two-way synced one — every local write is auto-enqueued to the outbox and every pulled server change is auto-applied back. Client-tier providers (SQLite, LiteDB, IndexedDB). Learn more - .NET Aspire integration —
Shiny.DocumentDb.Aspire.Hosting/.Client/.Orleansmake the backend a deployment decision:builder.AddPostgresDocumentStore("orders").WithSeeder(...)in the AppHost picks the provider and gates seeding; the consuming service callsbuilder.AddDocumentStore("orders")for the keyed store wired with health checks + OpenTelemetry.builder.AddDocumentDbAdmin()brings the admin UI up alongside them, already connected to every referenced store. Learn more - Admin UI — ShinyDocDbMyAdmin, a phpMyAdmin-style web front end shipped as a container image (
ghcr.io/shinyorg/shiny-docdb-myadmin). Browse documents in a sampled-column grid with JSON-path filters, edit them as JSON, inspect the inferred structure and create/drop indexes in one click, diff and restore temporal versions, map GeoJSON, preview blobs, stream import/export (JSON, NDJSON, CSV, envelope), and run parameterised SQL. Relational providers. Learn more
-
Install the NuGet packages
Install the core package plus your provider:
Terminal window dotnet add package Shiny.DocumentDb.SqliteTerminal window dotnet add package Shiny.DocumentDb.Sqlite.SqlCipherTerminal window dotnet add package Shiny.DocumentDb.SqlServerTerminal window dotnet add package Shiny.DocumentDb.MySqlTerminal window dotnet add package Shiny.DocumentDb.PostgreSqlTerminal window dotnet add package Shiny.DocumentDb.OracleTerminal window dotnet add package Shiny.DocumentDb.MongoDbTerminal window dotnet add package Shiny.DocumentDb.DuckDbTerminal window dotnet add package Shiny.DocumentDb.IndexedDbEach provider package includes the core
Shiny.DocumentDbpackage automatically — which now bundles the dependency-injection registration (AddDocumentStore,AddDocumentContext, seeding) and OpenTelemetry instrumentation, so there’s no separate package to install. -
Register with dependency injection:
using Shiny.DocumentDb;services.AddDocumentStore(opts =>{opts.DatabaseProvider = new SqliteDatabaseProvider("Data Source=mydata.db");});Just swap the provider for your database:
opts.DatabaseProvider = new SqliteDatabaseProvider("Data Source=mydata.db");opts.DatabaseProvider = new SqlCipherDatabaseProvider("mydata.db", "mySecretKey");opts.DatabaseProvider = new SqlServerDatabaseProvider("Server=localhost;Database=mydb;Trusted_Connection=true;");opts.DatabaseProvider = new MySqlDatabaseProvider("Server=localhost;Database=mydb;User=root;Password=pass;");opts.DatabaseProvider = new PostgreSqlDatabaseProvider("Host=localhost;Database=mydb;Username=postgres;Password=pass;");opts.DatabaseProvider = new OracleDatabaseProvider("User Id=myuser;Password=pass;Data Source=localhost:1521/FREEPDB1");opts.DatabaseProvider = new DuckDbDatabaseProvider("Data Source=mydata.duckdb");MongoDB uses its own options class — register the store directly with the DI container:
builder.Services.AddSingleton(new MongoDbDocumentStoreOptions{ConnectionString = "mongodb://localhost:27017",DatabaseName = "mydb"});builder.Services.AddSingleton<IDocumentStore, MongoDbDocumentStore>();For multiple databases, register named stores using .NET keyed services:
services.AddDocumentStore("users", opts =>{opts.DatabaseProvider = new SqliteDatabaseProvider("Data Source=users.db");});services.AddDocumentStore("analytics", opts =>{opts.DatabaseProvider = new PostgreSqlDatabaseProvider("Host=...");});Inject via
[FromKeyedServices("name")]or resolve dynamically withIDocumentSessionFactory:public class MyService([FromKeyedServices("users")] IDocumentStore userStore,[FromKeyedServices("analytics")] IDocumentStore analyticsStore) { }// Or dynamically:public class MyService(IDocumentSessionFactory stores){void DoWork() => stores.GetStore("users").Insert(...);}For multi-tenant applications, two isolation strategies are available:
// Shared-table: single database, automatic TenantId column filteringservices.AddSingleton<ITenantResolver, MyTenantResolver>();services.AddDocumentStore(opts =>{opts.DatabaseProvider = new PostgreSqlDatabaseProvider("Host=...");}, multiTenant: true);// ...or a named/keyed shared-table store (resolve with [FromKeyedServices("orders")]):services.AddDocumentStore("orders", opts =>{opts.DatabaseProvider = new PostgreSqlDatabaseProvider("Host=...");}, multiTenant: true);// Tenant-per-database: separate database per tenant (scoped IDocumentStore)services.AddSingleton<ITenantResolver, MyTenantResolver>();services.AddMultiTenantDocumentStore(tenantId => new DocumentStoreOptions{DatabaseProvider = new SqliteDatabaseProvider($"Data Source={tenantId}.db")});Both require an
ITenantResolverimplementation:public class MyTenantResolver(IHttpContextAccessor http) : ITenantResolver{public string GetCurrentTenant()=> http.HttpContext?.User.FindFirst("tenant_id")?.Value?? throw new InvalidOperationException("No tenant context");}Or instantiate directly (no DI needed):
// Quick setup (SQLite convenience class)var store = new SqliteDocumentStore("Data Source=mydata.db");// Full optionsvar store = new SqliteDocumentStore(new DocumentStoreOptions{DatabaseProvider = new SqliteDatabaseProvider("Data Source=mydata.db")});// Quick setupvar store = new SqlCipherDocumentStore("mydata.db", "mySecretKey");// Full optionsvar store = new SqlCipherDocumentStore(new DocumentStoreOptions{DatabaseProvider = new SqlCipherDatabaseProvider("mydata.db", "mySecretKey")});var store = new DocumentStore(new DocumentStoreOptions{DatabaseProvider = new SqlServerDatabaseProvider("Server=localhost;Database=mydb;Trusted_Connection=true;")});var store = new DocumentStore(new DocumentStoreOptions{DatabaseProvider = new MySqlDatabaseProvider("Server=localhost;Database=mydb;User=root;Password=pass;")});var store = new DocumentStore(new DocumentStoreOptions{DatabaseProvider = new PostgreSqlDatabaseProvider("Host=localhost;Database=mydb;Username=postgres;Password=pass;")});var store = new DocumentStore(new DocumentStoreOptions{DatabaseProvider = new DuckDbDatabaseProvider("Data Source=mydata.duckdb")});var store = new MongoDbDocumentStore(new MongoDbDocumentStoreOptions{ConnectionString = "mongodb://localhost:27017",DatabaseName = "mydb"}); -
Inject
IDocumentStoreand start using it:public class MyService(IDocumentStore store){public async Task SaveUser(User user){await store.Insert(user); // Id auto-generated for Guid/int/long; string Ids must be set}public async Task<User?> GetUser(string id){return await store.Get<User>(id);}public async Task<IReadOnlyList<User>> GetActiveUsers(){return await store.Query<User>().Where(u => u.IsActive).OrderBy(u => u.Name).ToList();}}
Configuration Options
Section titled “Configuration Options”| Property | Type | Default | Description |
|---|---|---|---|
DatabaseProvider |
IDatabaseProvider (required) |
— | The database provider to use (e.g. SqliteDatabaseProvider, SqlCipherDatabaseProvider, SqlServerDatabaseProvider, MySqlDatabaseProvider, PostgreSqlDatabaseProvider, DuckDbDatabaseProvider). LiteDB, CosmosDB, MongoDB, and IndexedDB use their own options classes. |
TableName |
string |
"documents" |
Default table name for all document types not mapped via MapTypeToTable |
TypeNameResolution |
TypeNameResolution |
ShortName |
How type names are stored (ShortName or FullName) |
JsonSerializerOptions |
JsonSerializerOptions? |
null |
JSON serialization settings. When a JsonSerializerContext is attached as the TypeInfoResolver, all methods auto-resolve type info from the context |
UseReflectionFallback |
bool |
true |
When false, throws InvalidOperationException if a type can’t be resolved from the configured TypeInfoResolver instead of falling back to reflection. Recommended for AOT deployments |
Logging |
Action<string>? |
null |
Callback invoked with every SQL statement executed |
TenantIdAccessor |
Func<string>? |
null |
When set, enables shared-table multi-tenancy. All queries are filtered by TenantId and all inserts include the TenantId value. A dedicated TenantId column and index are created automatically |
Table-Per-Type Mapping
Section titled “Table-Per-Type Mapping”By default all document types share a single table. Use MapTypeToTable to give a type its own dedicated table. Tables are lazily created on first use. Two types cannot map to the same custom table.
var store = new DocumentStore(new DocumentStoreOptions{ DatabaseProvider = new SqliteDatabaseProvider("Data Source=mydata.db"), TableName = "docs" // change the default table name (optional)}.MapTypeToTable<Order>("orders") // explicit table name.MapTypeToTable<AuditLog>() // auto-derived table name "AuditLog"// User stays in the default "docs" table);Custom Id property
Section titled “Custom Id property”By default every document type must have a property named Id. Override that with a custom property using either MapTypeToTable<T>(...) (combined with a dedicated table) or MapIdProperty<T>(...) (the type stays in the default shared table). The two are independent — use either, both, or neither.
var store = new DocumentStore(new DocumentStoreOptions{ DatabaseProvider = new SqliteDatabaseProvider("Data Source=mydata.db")}// Dedicated table + custom Id.MapTypeToTable<Sensor>("sensors", s => s.DeviceKey) // Guid DeviceKey as Id.MapTypeToTable<Tenant>("tenants", t => t.TenantCode) // string TenantCode as Id// Default shared table + custom Id.MapIdProperty<BlogPost>(p => p.Slug) // string Slug as Id);MapTypeToTable and MapIdProperty overloads
Section titled “MapTypeToTable and MapIdProperty overloads”| Overload | Description |
|---|---|
MapTypeToTable<T>() |
Auto-derive table name from type name |
MapTypeToTable<T>(string tableName) |
Explicit table name |
MapTypeToTable<T>(Expression<Func<T, object>> idProperty) |
Auto-derive table + custom Id |
MapTypeToTable<T>(string tableName, Expression<Func<T, object>> idProperty) |
Explicit table + custom Id |
MapIdProperty<T>(Expression<Func<T, object>> idProperty) |
Custom Id only — type stays in the default shared table |
MapIdProperty<T>(string propertyName) |
AOT-safe string overload |
All overloads return DocumentStoreOptions for fluent chaining. Duplicate table names throw InvalidOperationException.
DI Registration with Table Mapping
Section titled “DI Registration with Table Mapping”services.AddDocumentStore(opts =>{ opts.DatabaseProvider = new SqliteDatabaseProvider("Data Source=mydata.db"); opts.MapTypeToTable<User>(); opts.MapTypeToTable<Order>("orders"); opts.MapTypeToTable<Sensor>("sensors", s => s.DeviceKey);});AI Coding Assistant
Section titled “AI Coding Assistant”Step 1 — Add the marketplace:
claude plugin marketplace add shinyorg/skillsStep 2 — Install the plugin:
claude plugin install shiny-data@shinyStep 1 — Add the marketplace:
copilot plugin marketplace add https://github.com/shinyorg/skillsStep 2 — Install the plugin:
copilot plugin install shiny-data@shiny

