Rinsen.DatabaseInstaller 0.9.0

dotnet add package Rinsen.DatabaseInstaller --version 0.9.0
                    
NuGet\Install-Package Rinsen.DatabaseInstaller -Version 0.9.0
                    
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="Rinsen.DatabaseInstaller" Version="0.9.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Rinsen.DatabaseInstaller" Version="0.9.0" />
                    
Directory.Packages.props
<PackageReference Include="Rinsen.DatabaseInstaller" />
                    
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 Rinsen.DatabaseInstaller --version 0.9.0
                    
#r "nuget: Rinsen.DatabaseInstaller, 0.9.0"
                    
#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 Rinsen.DatabaseInstaller@0.9.0
                    
#: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=Rinsen.DatabaseInstaller&version=0.9.0
                    
Install as a Cake Addin
#tool nuget:?package=Rinsen.DatabaseInstaller&version=0.9.0
                    
Install as a Cake Tool

Rinsen.DatabaseInstaller

Build NuGet version License: MIT

Rinsen.DatabaseInstaller is a database installer and version handler for SQL Server. You define your database schema and changes in C# using a fluent API, and the installer creates the database, applies your versioned changes in order, and keeps track of which version is installed.

Features

  • Versioned migrations — every schema change is a DatabaseVersion with a version number; only versions newer than the installed one are applied
  • Fluent C# API — define tables, columns and indexes in code with automatic C# → SQL Server type inference, instead of raw SQL scripts
  • Logins, users and roles — create SQL Server logins, database users and role memberships as part of the installation
  • Data seeding — optional seed step that runs after a successful installation
  • Preview mode — inspect the SQL that would be run, without touching the database
  • Hosted anywhere — runs as a plain console app or as an Aspire service

Requirements

  • .NET 11
  • SQL Server (uses Microsoft.Data.SqlClient)

Getting started

1. Configure the installer

The installer is driven by configuration (appsettings.json, environment variables or any other Microsoft.Extensions.Configuration source):

{
  "Command": "Install",
  "DatabaseName": "SampleDb",
  "Schema": "dbo",
  "ConnectionStringName": "TestDb",
  "ConnectionStrings": {
    "TestDb": "Server=localhost;User Id=appuser;Password=YourStrongPassword;Encrypt=Mandatory"
  }
}

Connection string security. Encrypt=Mandatory is the default in recent .NET, so connections are TLS-encrypted unless you explicitly opt out — do not disable it just to make a local server work. Use a least-privilege login (a user with dbcreator rights is enough for creating the database) instead of sa, and never store passwords in source control — read them from environment variables, a user-secrets store or a vault. Only set TrustServerCertificate=True for throwaway local development against a SQL Server that has a self-signed certificate; in production use a valid certificate.

Setting Description
Command What to do: Install, Preview, ShowAll or CurrentState (see Commands)
DatabaseName Name of the database to create or update
Schema Schema to install into, e.g. dbo
ConnectionStringName Key under ConnectionStrings that holds the connection string to the server

2. Wire up the entry point

using Rinsen.DatabaseInstaller;

public static class Program
{
    public static Task Main()
    {
        var installerHostBuilder = InstallerHost.CreateBuilder();

        installerHostBuilder.AddServices(services =>
        {
            // Register application specific services here
            services.AddSingleton<MyService>();
        });

        installerHostBuilder.AddDatabaseSetup<DatabaseSetup>();
        installerHostBuilder.AddDataSeed<DataSeed>(); // optional

        return installerHostBuilder.Start();
    }
}

DatabaseSetup declares which versions to install:

public class DatabaseSetup : IDatabaseSetup
{
    public void DatabaseVersionsToInstall(List<DatabaseVersion> databaseVersions, IConfiguration configuration)
    {
        databaseVersions.Add(new CreateTables());
    }
}

3. Define your database versions

A DatabaseVersion is a class with a version number and a list of database changes. The installation name defaults to the class namespace:

public class CreateTables : DatabaseVersion
{
    public CreateTables()
        : base(1)
    {
    }

    public override void AddDbChanges(List<IDbChange> dbChangeList)
    {
        // Table name defaults to the type name + "s" => "Customers"
        var table = dbChangeList.AddNewTable<Customer>();

        table.AddAutoIncrementColumn(m => m.Id);
        table.AddColumn(m => m.Name).Unique();
        table.AddColumn(m => m.Email);
    }
}

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}

This generates:

CREATE TABLE [SampleDb].[dbo].[Customers]
(
  [Id] int IDENTITY(1,1) PRIMARY KEY,
  [Name] nvarchar(1) NOT NULL UNIQUE,
  [Email] nvarchar(1) NULL
)

For a complete working project — including data seeding and an Aspire App Host that starts SQL Server — see sample/InstallationSampleConsoleApp and sample/AspireDatabaseInstaller.AppHost.

Commands

Command Description
Install Waits until the SQL Server is reachable, creates the database if it does not exist, then applies all not-yet-installed versions in a single transaction
Preview Prints the SQL that would be applied for each pending version, without applying anything
ShowAll Prints the SQL for all versions of all installations
CurrentState Lists the installed version per installation name

Defining database changes

All changes are added to the dbChangeList inside AddDbChanges using extension methods on List<IDbChange>.

Tables and columns

var table = dbChangeList.AddNewTable<Customer>();

table.AddAutoIncrementColumn(m => m.Id, startValue: 1, increment: 1, primaryKey: true);
table.AddColumn(m => m.Name);
table.AddColumn(m => m.Bio, 500);            // length
table.AddColumn(m => m.Price, 10, 2);        // precision, scale
table.SetPrimaryKeyNonClustered();           // only if the primary key is not clustered

Reference types (string) and nullable value types (int?, Guid?, ...) produce NULL columns; non-nullable value types produce NOT NULL columns.

C# → SQL Server type mapping
C# type SQL Server type
bool / bool? bit
byte / byte? tinyint
short / short? smallint
int / int? int
long / long? bigint
decimal / decimal? decimal(18,2) (or decimal(p,s) when length/precision is given)
double / double? float
Guid / Guid? uniqueidentifier
DateTime / DateTime? datetime
DateTimeOffset / DateTimeOffset? datetimeoffset
string nvarchar(1) (or nvarchar(n) with a length, nvarchar(max) with int.MaxValue)
byte[] / byte?[] varbinary (or varbinary(n) with a length)
Enums tinyint

Column constraints

Every AddColumn returns a ColumnBuilder that can be chained:

table.AddColumn(m => m.Email).Unique("UK_Customers_Email");
table.AddColumn(m => m.IsActive).NotNull();
table.AddColumn(m => m.Status).Null();
table.AddColumn(m => m.OwnerId).ForeignKey<Customer>(m => m.Id);
Method Effect
NotNull() / Null() Override nullability
PrimaryKey() / PrimaryKey("PK_Customers") Mark as primary key (chain on several columns for composite keys)
Unique() / Unique("UK_Customers_Email") Unique constraint, optionally named
Clustered() Clustered column (only allowed when the primary key is non-clustered)
ForeignKey("Customers", "Id") / ForeignKey<Customer>(m => m.Id) Foreign key reference
AutoIncrement(startValue, increment, primaryKey) Identity column

Indexes

// Non-clustered index
dbChangeList.AddNewIndex<Customer>("IX_Customers_Email")
    .AddColumn(m => m.Email);

// Unique index
dbChangeList.AddNewUniqueIndex<Customer>("UK_Customers_Name")
    .AddColumn(m => m.Name);

// Clustered index
dbChangeList.AddNewClusteredIndex<Customer>("CX_Customers_ExternalId")
    .AddColumn(m => m.ExternalId);

// Unique clustered index
dbChangeList.AddNewUniqueClusteredIndex<Customer>("UCX_Customers_NaturalKey")
    .AddColumn(m => m.NaturalKey);

The table name is derived from the type (Customer → Customers) or can be passed explicitly: AddNewIndex("IX_Customers_Email", "Customers").

Altering existing tables

Use AddNewTableAlteration to add, alter or drop columns on a table created by a previous version:

var alteration = dbChangeList.AddNewTableAlteration<Customer>();

alteration.AddColumn(m => m.Phone);          // ADD COLUMN
alteration.AlterColumn(m => m.Email, 200);   // ALTER COLUMN
alteration.DropColumn(m => m.Legacy);        // DROP COLUMN

Logins, users and roles

Create SQL Server logins, database users and role memberships as part of a version:

var databaseSettings = dbChangeList.AddNewDatabaseSettings();

databaseSettings
    .CreateLogin("MyLogin", "MyP@ssw0rd")   // or CreateLogin("MyLogin") for a random password
    .WithUser("MyUser")
    .AddRoleMembershipDataReader()
    .AddRoleMembershipDataWriter();

Seeding data

Optionally register a data seed. It runs once, after a successful installation, and receives the same InstallerOptions:

public class DataSeed : IDataSeed
{
    private readonly InstallerOptions _installerOptions;

    public DataSeed(InstallerOptions installerOptions)
    {
        _installerOptions = installerOptions;
    }

    public async Task SeedData()
    {
        using var connection = new SqlConnection(_installerOptions.ConnectionString);
        await connection.OpenAsync();

        // Insert your seed data...
    }
}

Index naming convention

Prefix Meaning
PK_ Primary keys
UK_ Unique keys
IX_ Non-clustered, non-unique indexes
UX_ Unique indexes

General pattern:

<index or key type>_<table name>_<column 1>_<column 2>_<column n>

Example: UK_Customers_Email, IX_Customers_CreatedOn

Current limitations

  • No down-migrations or rollbacks — only forward version installation is supported; GetDownCommands and RollbackVersions are not implemented
  • Check constraints — ColumnBuilder.Check() exists but is not implemented and will throw at install time
  • Default values — ColumnBuilder.DefaultValue() exists but is not implemented and will throw at install time
  • One version per number per installation name — duplicate version numbers within an installation name are rejected
  • SQL Server only — no other database providers

License

MIT — see LICENSE.

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

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.9.0 82 11/18/2026
0.8.0 592 12/8/2025
0.7.2 259 10/9/2025
0.7.1 240 10/9/2025
0.7.0 359 4/15/2025
0.6.8 303 2/11/2024
0.6.7 425 4/25/2023
0.6.6 324 4/25/2023
0.6.5 331 4/25/2023
0.6.4 386 3/14/2023
0.6.3 368 3/13/2023
0.6.2 417 2/28/2023
0.6.1 455 1/16/2023
0.6.0 419 1/16/2023
0.5.1 607 11/8/2021
0.4.15 692 1/19/2021
Loading failed