Fluent Migrator 在错误的数据库中创建了表版本信息

问题描述

当我连接到 sql Server 时,Fluent Migrator 在 Version Info 数据库中创建了一个 master 表,但是我自己使用 sql 脚本创建了该数据库,然后应用程序因为找不到而掉线version info 表。

我需要做什么才能让我的脚本正确运行?

C# 代码

static void Main(string[] args)
{
    string connString = @"Server=localhost\sqlEXPRESS;Trusted_Connection=True;";
    //Migration
}

private static IServiceProvider CreateServices(string connString)
{
    return new ServiceCollection()
        // Add common FluentMigrator services
        .AddFluentMigratorCore()
        .ConfigureRunner(rb => rb
            .AddsqlServer()
            // Set the connection string
            .WithGlobalConnectionString(connString)
            // Define the assembly containing the migrations
            .ScanIn(Assembly.GetExecutingAssembly()).For.Migrations())
        // Enable logging to console in the FluentMigrator way
        .AddLogging(lb => lb.AddFluentMigratorConsole())
        // Build the service provider
        .BuildServiceProvider(false);
}

/// <summary>
/// Update the database
/// </summary>
private static void UpdateDatabase(IServiceProvider serviceProvider)
{
    // Instantiate the runner
    runner.MigrateUp(1610594913);
    runner.MigrateUp(1610594914);
}

[Migration(1610594913,TransactionBehavior.None)]
public class Migration_1610594911 : Migration
{
    public override void Down()
    {
        Execute.sql("DROP DATABASE siteDB");
    }

    public override void Up()
    {
        Execute.sql(@"CREATE DATABASE siteDB;");
    }
}

第二条 sql

[Migration(1610594914)]
public class CreateTablesMigation : Migration
{
    public override void Down()
    {
    }

    public override void Up()
    {
        Execute.sql(@"
USE siteDB;
CREATE TABLE[AspNetRoles]
...");
    }
}

解决方法

您在 FluentMigrator 之外创建数据库,然后通过提供连接字符串参数 Initial Catalog=xxxDatabase=xxx(它们的意思相同)指定要使用的数据库

在运行迁移之前,使用 SqlCommand 以与运行任何普通 SQL 相同的方式创建数据库