Rmp.ReadonlyDb.CodeGen
2026.11.7
See the version list below for details.
dotnet add package Rmp.ReadonlyDb.CodeGen --version 2026.11.7
NuGet\Install-Package Rmp.ReadonlyDb.CodeGen -Version 2026.11.7
<PackageReference Include="Rmp.ReadonlyDb.CodeGen" Version="2026.11.7" />
<PackageVersion Include="Rmp.ReadonlyDb.CodeGen" Version="2026.11.7" />
<PackageReference Include="Rmp.ReadonlyDb.CodeGen" />
paket add Rmp.ReadonlyDb.CodeGen --version 2026.11.7
#r "nuget: Rmp.ReadonlyDb.CodeGen, 2026.11.7"
#:package Rmp.ReadonlyDb.CodeGen@2026.11.7
#addin nuget:?package=Rmp.ReadonlyDb.CodeGen&version=2026.11.7
#tool nuget:?package=Rmp.ReadonlyDb.CodeGen&version=2026.11.7
Rmp.ReadonlyDb
Turn any database into a fast, readonly, in-memory queryable store — with lazy loading, code generation, and file-based snapshots.
By Rubicon Microproducts. Questions and bug reports: rubiconmp/public-issues.
The Problem
Many applications use a database that is effectively readonly — lookup tables, reference data, configuration, catalogs, etc. Yet they still pay the cost of:
- Live database connections for every query
- Network latency on every request
- Connection pool exhaustion under load
- Full ORM overhead (change tracking, identity maps) for data that never changes
- Slow startup when the app preloads reference data
The Solution
| Capability | Package | What it does |
|---|---|---|
| 1. Offline → In-Memory | Rmp.ReadonlyDb.Snapshot |
Reads DB offline, creates IQueryable<T> / List<T> in memory |
| 2. Offline → Code | Rmp.ReadonlyDb.CodeGen |
Reads DB offline, generates compilable C# files (POCOs + static data) |
| 3. Runtime → In-Memory | Rmp.ReadonlyDb.Runtime |
Connects at runtime, mirrors to in-memory with dump-to-file option |
| 4. Lazy Loading | Built into Core | Loads entities on-demand — startup is instant, first access per table is fast |
Packages
| Package | Description |
|---|---|
Rmp.ReadonlyDb.Core |
Core interfaces, schema discovery, lazy entity sets, mapping |
Rmp.ReadonlyDb.Snapshot |
Offline snapshot → in-memory IQueryable context |
Rmp.ReadonlyDb.CodeGen |
Database → compilable C# source files |
Rmp.ReadonlyDb.Runtime |
Live DB → in-memory mirror with auto-dump |
Installation
# Pick your provider(s) — each one brings in Rmp.ReadonlyDb.Core automatically:
dotnet add package Rmp.ReadonlyDb.Snapshot
dotnet add package Rmp.ReadonlyDb.CodeGen
dotnet add package Rmp.ReadonlyDb.Runtime
Supported frameworks:
| Your project | Package build used | PostgreSQL driver |
|---|---|---|
| .NET 10+ | net10.0 |
Npgsql 10 |
| .NET 8, .NET 9 | net8.0 |
Npgsql 10 |
| .NET Framework 4.6.2 – 4.8.1 | net462 |
Npgsql 8 |
| .NET Core 2.0 – 3.1, .NET 5 – 7, Mono, other netstandard2.0 platforms | netstandard2.0 |
Npgsql 8 |
.NET Framework 4.6.1 and older are not supported (Microsoft.Data.SqlClient needs 4.6.2).
Quick Start
Capability 1: Offline Snapshot → In-Memory IQueryable
// Context is created instantly — no DB connection yet
await using var ctx = new SnapshotDbContext(connectionString, DatabaseDialect.SqlServer);
// First access to Products triggers lazy load of ONLY the Products table
var expensive = ctx.Set<Product>()
.Where(p => p.Price > 100)
.OrderBy(p => p.Name)
.ToList();
// Dynamic/untyped access by table name
var rows = ctx.Set("dbo.LookupCodes");
await rows.EnsureLoadedAsync();
// Export to files for offline use later
await ctx.ExportToJsonAsync("./snapshots");
Load from Snapshot Files (no DB needed)
await using var ctx = new FileSnapshotDbContext("./snapshots");
var products = ctx.Set<Product>();
var list = await products.ToListAsync();
Capability 2: Generate Compilable C# Files
var generator = new DatabaseCodeGenerator();
await generator.GenerateAsync(new CodeGenOptions
{
ConnectionString = connectionString,
Dialect = DatabaseDialect.SqlServer,
Namespace = "MyApp.ReadonlyData",
OutputDirectory = "./Generated",
IncludeTables = ["dbo.Products", "dbo.Categories"], // empty = all tables
EmbedData = true, // Embed row data (as compact .rodb resources by default)
GenerateNavigations = true, // FK-based navigation properties
MaxRowsPerTable = 5000 // Safety limit
});
Generated output:
Generated/
├── Product.cs ← POCO entity ([Table], [Column], [Key] attributes)
├── ProductData.cs ← Loader for Product rows
├── ProductData.rodb ← Product rows (compact binary)
├── Category.cs / CategoryData.cs / CategoryData.rodb
├── ReadonlyDataContextStorage.cs ← Shared .rodb reader
└── ReadonlyDataContext.cs ← Static context with lazy, thread-safe collections
Embed the data files in the project that compiles the generated code:
<ItemGroup>
<EmbeddedResource Include="Generated\*.rodb" />
</ItemGroup>
Usage in your app:
// Each table is materialized on first access
var categories = ReadonlyDataContext.Categories;
var product = ReadonlyDataContext.Products.First(p => p.Id == 42);
// Populate FK navigation properties (once; thread-safe)
ReadonlyDataContext.WireNavigations();
var categoryName = product.Category?.Name;
Notes:
- Generated code only uses the .NET base library — your app does not need any Rmp.ReadonlyDb package at runtime.
- Older projects: by default the generated code uses C# 10 (
initproperties, nullable annotations) and needs .NET 6+. For .NET Framework or netstandard2.0 projects, setCompatibility = GeneratedCodeCompatibility.Legacy: the output then builds with C# 7.3 (settable properties, no nullable annotations) on .NET Framework 4.6.2 and later. - Output is deterministic (no timestamps), so regenerated files diff cleanly in source control.
- Names are always valid C#: keywords, spaces and leading digits are escaped, and clashes (e.g.
dbo.Productsandsales.Products) get unique names. - Size: data is streamed from the database to disk, so generation memory stays flat however big the tables are.
The only limits are .NET's own: one assembly must stay under ~2 GB, and one table under ~2.1 billion rows
(one in-memory list). Past 2 GB the generator stops with
GeneratedCodeTooLargeException, listing the largest tables. Split the tables across several projects withIncludeTables/ExcludeTables. DataFormat = GeneratedDataFormat.CSharpLiteralswrites rows as C# initializers instead (no project-file change). .NET caps string literals at ~16 MB per assembly and big initializers compile slowly, so use it only for small lookup tables. The generator checks that cap up front rather than letting the compiler fail with CS8103.- Loading a table materializes all of its rows in memory on first access; that is the point of the library.
- Generated entity classes also work with
Set<T>()on the Snapshot and Runtime contexts.
Capability 3: Runtime In-Memory with Dump-to-File
await using var ctx = new RuntimeDbContext(new RuntimeDbOptions
{
ConnectionString = connectionString,
Dialect = DatabaseDialect.SqlServer,
AutoDumpDirectory = "./data-cache", // Auto-saves after loading
PreferDumpOverLive = true, // First load uses the dump if it exists
RefreshInterval = TimeSpan.FromHours(1) // Optional periodic refresh (always from the live DB)
});
ctx.RefreshFailed += (_, e) => logger.LogWarning(e.Exception, "Reference data refresh failed");
// Lazy: only loads the Categories table
var categories = ctx.Set<Category>();
await categories.EnsureLoadedAsync();
// LINQ works directly
var active = categories.Where(c => c.Description != null).ToList();
// Explicit dump
await ctx.DumpToFilesAsync();
// Manual refresh: re-reads loaded tables and swaps the data in place
await ctx.RefreshAsync();
Register RuntimeDbContext as a singleton. Sets you got from Set<T>() stay valid across refreshes and always
show the latest successfully loaded data; if a refresh fails, the previous data is kept.
Dump files contain your table data in plain JSON. Put AutoDumpDirectory somewhere only the app can read.
Connection strings and credentials are never written to dumps.
Capability 4: Lazy Loading (Built-in)
All providers use lazy loading by default:
var ctx = new SnapshotDbContext(connStr, DatabaseDialect.SqlServer);
// ✅ Instant — no DB connection, no data loaded
var products = ctx.Set<Product>(); // just registers the set
var orders = ctx.Set<Order>(); // just registers the set
// ✅ First enumeration triggers load of ONLY that table
var count = products.Count(); // loads Products, NOT Orders
// ✅ Preload specific tables if you want
await ctx.PreloadAsync(default, typeof(Product), typeof(Category));
// ✅ Or preload everything
await ctx.PreloadAllAsync();
Enumerating a set synchronously before it is loaded blocks the calling thread while the table loads.
In async code (e.g. ASP.NET Core), call await set.EnsureLoadedAsync() or PreloadAllAsync() at startup first.
Mapping Rules
Table → class (used by Set<T>()):
[Table("name", Schema = "schema")]on the class, if present.- Otherwise a table whose name equals the class name (
Product↔Product). - Otherwise a table whose singularized name equals the class name (
Product↔Products,OrderItem↔order_items).
If two tables match (e.g. dbo.Products and sales.Products), you get an error asking for [Table].
Column → property:
[Column("name")]on the property.- Otherwise same name, ignoring case.
- Otherwise same name ignoring case,
_,-and spaces (first_name→FirstName).
Properties with [NotMapped] are skipped. A value that can't be converted to the property type throws
EntityMappingException naming the table column and property — data is never silently dropped.
FindAsync(key) uses the property marked [Key], or a property named Id.
Architecture
Rmp.ReadonlyDb.Core/
├── Schema/ → Database schema model (tables, columns, relationships)
│ ├── ColumnSchema.cs
│ ├── TableSchema.cs
│ ├── RelationshipSchema.cs
│ ├── DatabaseSchema.cs
│ └── DatabaseDialect.cs
├── Discovery/ → Schema + data readers (ADO.NET)
│ ├── DatabaseSchemaDiscovery.cs
│ ├── AdoTableDataReader.cs
│ └── DbDialects.cs → Connections, quoting, dialect detection
├── Lazy/ → Lazy loading infrastructure
│ ├── LazyEntitySet.cs → IQueryable<T> with deferred load
│ └── LazyAsync.cs → Async lazy value wrapper
├── Mapping/ → Row-to-entity mapping
│ ├── EntityMapper.cs
│ ├── ValueConverter.cs → Culture-independent value conversion
│ ├── EntityTableResolver.cs → Entity type → table
│ └── NamingConventions.cs
├── Serialization/ → Snapshot file I/O
│ └── JsonSnapshotSerializer.cs
├── ReadonlyDbContextBase.cs → Shared context logic (caching, preload, reload)
├── IReadonlyDbContext.cs → Main entry point interface
├── IReadonlyEntitySet.cs → Queryable entity set interface
├── ISchemaDiscovery.cs → Schema discovery contract
├── ITableDataReader.cs → Data reading contract
├── ISnapshotSerializer.cs → Serialization contract
└── ICodeGenerator.cs → Code generation contract
Rmp.ReadonlyDb.Snapshot/ → Capability 1: offline → in-memory
├── SnapshotDbContext.cs → DB → in-memory IQueryable
└── FileSnapshotDbContext.cs → File → in-memory IQueryable
Rmp.ReadonlyDb.CodeGen/ → Capability 2: offline → C# files
├── DatabaseCodeGenerator.cs → Generates POCOs + data + static context
├── CSharpLiterals.cs → Lossless, culture-independent literals
└── NameMap.cs → Unique, valid C# names
Rmp.ReadonlyDb.Runtime/ → Capability 3: live → in-memory + dump
├── RuntimeDbContext.cs → Live DB mirror with auto-dump
└── RuntimeDbOptions.cs → Configuration
Supported Databases
| Database | Dialect | Schema Discovery | Data Reading |
|---|---|---|---|
| SQL Server | DatabaseDialect.SqlServer |
✅ sys.* views |
✅ Microsoft.Data.SqlClient |
| PostgreSQL | DatabaseDialect.PostgreSql |
✅ information_schema + pg_catalog |
✅ Npgsql |
Only base tables are read (no views). Rows are read in primary-key order. SQL Server hierarchyid, geography and
geometry columns are read as strings, and timestamp/rowversion as byte[].
Build & Test
dotnet build
dotnet test # runs on .NET 10, .NET 8 and (on Windows) .NET Framework 4.8
# Run examples
dotnet run --project Rmp.ReadonlyDb.Examples -- help
dotnet run --project Rmp.ReadonlyDb.Examples -- snapshot "Server=.;Database=MyDb;Trusted_Connection=true"
dotnet run --project Rmp.ReadonlyDb.Examples -- codegen "Server=.;Database=MyDb;Trusted_Connection=true"
dotnet run --project Rmp.ReadonlyDb.Examples -- runtime "Server=.;Database=MyDb;Trusted_Connection=true"
Integration tests (real SQL Server)
The integration tests are skipped unless READONLYDB_SQLSERVER holds a connection string. They only read from the database
(temp files are cleaned up) and cover discovery, a full snapshot round-trip with value comparison, typed mapping into
generated entities, generated code for the whole database, Runtime refresh/dump, and reading the largest table.
$env:READONLYDB_SQLSERVER = "Server=.\SQLEXPRESS;Database=CCM;Integrated Security=True;TrustServerCertificate=True"
dotnet test Rmp.ReadonlyDb.Tests --filter "FullyQualifiedName~Integration"
Design Decisions
- Lazy by default: No data or schema is loaded until first access.
Set<T>()returns instantly. - Thread-safe: Concurrent first access triggers a single load; refreshes swap data atomically.
- IQueryable: Entity sets implement
IQueryable<T>, so standard LINQ works directly. - No change tracking: This is intentionally readonly — no
SaveChanges(), no dirty tracking, no overhead. - Pluggable: All core contracts are interfaces (
ISchemaDiscovery,ITableDataReader,ISnapshotSerializer). - Convention-based mapping: See Mapping Rules; attributes override conventions.
Publishing to NuGet
# Pack only (outputs to ./nupkg/)
.\publish.ps1 -NoPush
# Pack + push to NuGet.org
.\publish.ps1 -ApiKey YOUR_API_KEY
# Pack with version override
.\publish.ps1 -ApiKey YOUR_API_KEY -Version 1.1.0
# Push to a custom feed
.\publish.ps1 -ApiKey YOUR_API_KEY -Source https://my-feed.example.com/v3/index.json
The script runs the tests first, then packs only the four library projects.
Versions are date-based (YYYY.M.D, set in Directory.Build.props) — bump the version before each publish.
Or manually:
# Pack the library projects
for p in Core Snapshot CodeGen Runtime; do dotnet pack Rmp.ReadonlyDb.$p -c Release --output ./nupkg; done
# Push to NuGet.org
dotnet nuget push "./nupkg/*.nupkg" --api-key YOUR_API_KEY --source https://api.nuget.org/v3/index.json --skip-duplicate
Packages produced:
| Package | NuGet ID |
|---|---|
| Core | Rmp.ReadonlyDb.Core |
| Snapshot | Rmp.ReadonlyDb.Snapshot |
| CodeGen | Rmp.ReadonlyDb.CodeGen |
| Runtime | Rmp.ReadonlyDb.Runtime |
Each package includes:
.nupkg— the package.snupkg— symbol package with SourceLink (enables step-into-source debugging)README.md— embedded package readme- XML documentation
Support
Report bugs and request features at github.com/rubiconmp/public-issues (mention "Rmp.ReadonlyDb" in the title). More from Rubicon Microproducts: rubiconmp.com.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. 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. |
| .NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
| .NET Framework | net461 was computed. net462 is compatible. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen40 was computed. tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETFramework 4.6.2
- Rmp.ReadonlyDb.Core (>= 2026.11.7)
-
.NETStandard 2.0
- Rmp.ReadonlyDb.Core (>= 2026.11.7)
-
net10.0
- Rmp.ReadonlyDb.Core (>= 2026.11.7)
-
net8.0
- Rmp.ReadonlyDb.Core (>= 2026.11.7)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
Release notes: https://github.com/rubiconmp/public-issues. Rubicon Microproducts: https://rubiconmp.com/