Nabs.Launchpad.Core.Migrations 10.0.219

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

Nabs Launchpad Core Migrations Library

A .NET 10 library providing interfaces and abstractions for database migration and seeding operations in the Nabs Launchpad framework.

Overview

The Nabs.Launchpad.Core.Migrations library defines core interfaces and implementations for managing database initialization tasks including:

  • Database schema migrations using Entity Framework Core
  • Test data generation and seeding
  • Development environment data setup

This library provides a streamlined API using C# 13 extension types to configure SQL Server database migrations with minimal boilerplate.

Key Features

  • Migration Processing: Built-in IMigrationsProcessor implementation that automatically applies pending EF Core migrations
  • Seed Data Processing: ISeedDataProcessor interface for populating databases with initial or test data
  • Extension Types: Modern C# 13 extension type syntax for fluent configuration
  • Pooled DbContext Factory: Uses AddPooledDbContextFactory for efficient database context management
  • Async Support: All operations support cancellation tokens and async patterns
  • Framework Integration: Designed to work seamlessly with dependency injection and hosted services

Getting Started

1. Install the Package

Add a reference to Nabs.Launchpad.Core.Migrations in your project.

2. Configure Migrations in Program.cs

var builder = WebApplication.CreateBuilder(args);

// Configure SQL migrations with your DbContext and seed data processor
builder.AddSqlMigrations<ApplicationDbContext, UserSeedDataProcessor>("ApplicationDb");

var app = builder.Build();

3. Implement a Seed Data Processor

public class UserSeedDataProcessor : ISeedDataProcessor
{
    private readonly IDbContextFactory<ApplicationDbContext> _dbContextFactory;

    public UserSeedDataProcessor(IDbContextFactory<ApplicationDbContext> dbContextFactory)
    {
        _dbContextFactory = dbContextFactory;
    }

    public async Task ProcessAsync(CancellationToken stoppingToken)
    {
        using var dbContext = _dbContextFactory.CreateDbContext();
        
        if (await dbContext.Users.AnyAsync(stoppingToken))
            return; // Data already exists

        // Add seed data
        await dbContext.Users.AddAsync(new User { Name = "Admin" }, stoppingToken);
        await dbContext.SaveChangesAsync(stoppingToken);
    }
}

Core Interfaces and Components

ISeedDataProcessor

Defines a contract for processing seed data operations:

public interface ISeedDataProcessor
{
    Task ProcessAsync(CancellationToken stoppingToken);
}

Use this interface to implement classes that populate your database with:

  • Initial application data
  • Test data for development environments
  • Sample data for demonstrations

IMigrationsProcessor

Defines a contract for handling database migrations:

public interface IMigrationsProcessor
{
    Type DbContextType { get; }
    DatabaseFacade Database { get; }
    IEnumerable<string> ListMigrations();
    Task MigrateAsync(CancellationToken stoppingToken);
    DbContext CreateDbContext();
}

The library provides a built-in implementation (MigrationsProcessor<TDbContext>) that:

  • Checks for pending migrations before applying
  • Applies migrations only when needed
  • Uses IDbContextFactory<TDbContext> for efficient context management
  • Provides access to the underlying DatabaseFacade for advanced operations

MigrationsServices

A service class for managing multiple migration processors:

public class MigrationsServices
{
    public static List<ProcessorInfo> RegisteredProcessors { get; }
    public HostApplicationBuilder Builder { get; }
    public IEnumerable<IMigrationsProcessor> ListMigrationProcessors();
    public IEnumerable<MigrationInfo> ListMigrationsInfos();
    public Task RunAsync(CancellationToken stoppingToken);
}

Extension Methods

AddSqlMigrations

The AddSqlMigrations extension method configures SQL Server database migrations with a pooled DbContext factory:

builder.AddSqlMigrations<MyDbContext, MySeedDataProcessor>("MyDatabase");

This method:

  • Registers a pooled IDbContextFactory<TDbContext> with SQL Server configuration
  • Configures the migrations assembly from the seed data processor's assembly
  • Registers IMigrationsProcessor as a singleton
  • Registers ISeedDataProcessor as a singleton with automatic factory injection
  • Attempts to read connection string from IDesignTimeDbContextFactory if not found in configuration

Dependencies

  • .NET 10: Target framework
  • Microsoft.EntityFrameworkCore: Core EF abstractions
  • Microsoft.EntityFrameworkCore.SqlServer: SQL Server provider
  • Microsoft.Extensions.Hosting: Hosting abstractions
  • Bogus: Fake data generation library for creating realistic test data
  • Azure.Data.AppConfiguration: Azure App Configuration client
  • Aspire.Microsoft.Extensions.Configuration.AzureAppConfiguration: Aspire integration for Azure App Configuration

Usage Examples

Implementing ISeedDataProcessor with Bogus

public class UserSeedDataProcessor : ISeedDataProcessor
{
    private readonly IDbContextFactory<ApplicationDbContext> _dbContextFactory;
    private readonly Faker<User> _userFaker;

    public UserSeedDataProcessor(IDbContextFactory<ApplicationDbContext> dbContextFactory)
    {
        _dbContextFactory = dbContextFactory;
        _userFaker = new Faker<User>()
            .RuleFor(u => u.FirstName, f => f.Name.FirstName())
            .RuleFor(u => u.LastName, f => f.Name.LastName())
            .RuleFor(u => u.Email, f => f.Internet.Email());
    }

    public async Task ProcessAsync(CancellationToken stoppingToken)
    {
        using var dbContext = _dbContextFactory.CreateDbContext();
        
        if (await dbContext.Users.AnyAsync(stoppingToken))
            return; // Data already exists

        var users = _userFaker.Generate(100);
        await dbContext.Users.AddRangeAsync(users, stoppingToken);
        await dbContext.SaveChangesAsync(stoppingToken);
    }
}

Using in Hosted Service

public class DatabaseInitializationService : IHostedService
{
    private readonly IMigrationsProcessor _migrationsProcessor;
    private readonly ISeedDataProcessor _seedDataProcessor;

    public DatabaseInitializationService(
        IMigrationsProcessor migrationsProcessor,
        ISeedDataProcessor seedDataProcessor)
    {
        _migrationsProcessor = migrationsProcessor;
        _seedDataProcessor = seedDataProcessor;
    }

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        await _migrationsProcessor.MigrateAsync(cancellationToken);
        await _seedDataProcessor.ProcessAsync(cancellationToken);
    }

    public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}

Using MigrationsServices Directly

var migrationsServices = new MigrationsServices();
migrationsServices.Builder.AddSqlMigrations<MyDbContext, MySeedDataProcessor>("MyDb");

// List all migrations
foreach (var migrationInfo in migrationsServices.ListMigrationsInfos())
{
    Console.WriteLine($"{migrationInfo.Name}: {migrationInfo.Status}");
}

// Run migrations and seed data
await migrationsServices.RunAsync(cancellationToken);

Connection String Configuration

The AddSqlMigrations method reads connection strings from configuration. If no connection string is found, it attempts to get the connection string from an IDesignTimeDbContextFactory implementation, then falls back to a local SQL Server instance:

{
  "ConnectionStrings": {
    "ApplicationDb": "Server=myserver;Database=MyApp;..."
  }
}

Default fallback: Server=.;Database={name};Integrated Security=True;TrustServerCertificate=True;

Integration with Launchpad

This library is part of the larger Nabs Launchpad framework and integrates with:

  • Core.MigrationsCli: Command-line interface for managing migrations
  • Core.Testing.Silos: Provides test data for Orleans silo testing
  • Core.Persistence: Works with Entity Framework contexts for data operations
  • Core.Context: Integrates with application database contexts

Best Practices

  1. Environment-Specific Data: Only seed data appropriate for the current environment
  2. Idempotent Operations: Ensure seed operations can be run multiple times safely
  3. Performance Considerations: Use bulk operations for large datasets
  4. Error Handling: Implement proper error handling and logging
  5. Cancellation Support: Always respect cancellation tokens for graceful shutdowns
  6. Constructor Pattern: Seed data processors should accept IDbContextFactory<TDbContext> as their first constructor parameter

Contributing

This library follows the Nabs Launchpad coding standards:

  • Use C# 13 features and latest language constructs
  • Follow nullable reference types conventions
  • Implement proper async/await patterns
  • Include comprehensive unit tests

License

Copyright © Net Advantage Business Solutions

Product 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (3)

Showing the top 3 NuGet packages that depend on Nabs.Launchpad.Core.Migrations:

Package Downloads
Nabs.Launchpad.Core.Testing

Package Description

Nabs.Launchpad.Core.Testing.Silos

Package Description

Nabs.Launchpad.Core.MigrationsCli

Package Description

GitHub repositories

This package is not used by any popular GitHub repositories.