实体框架中的跨数据库迁移

本文关键字:数据库 迁移 框架 实体 | 更新日期: 2023-09-27 18:16:32

我希望我的应用程序与各种数据库,如MSSQL, MySQL和SQLite工作。通过更改配置中的连接字符串,连接工作得很好,我设法像这样应用数据库特定的配置:

public class ServerDbConfiguration : DbConfiguration
{
    public ServerDbConfiguration()
    {
        switch (ConfigurationManager.AppSettings["DatabaseProvider"].ToUpper())
        {
            case "MYSQL":
                SetHistoryContext("MySql.Data.MySqlClient", (conn, schema) => new ServerHistoryContext(conn, schema));
                break;
            default:
                break;
        }
    }
}

现在我正在寻找一种方法来实现相同的迁移。在对MSSQL数据库运行Add-Migration之后,我得到如下内容:

public partial class Initial : DbMigration
{
    public override void Up()
    {
        CreateTable(
            "dbo.Jobs",
            c => new
                {
                    id = c.Int(nullable: false, identity: true),
                    name = c.String(nullable: false, maxLength: 128),
                })
            .PrimaryKey(t => t.id);
        // ....
    }
}

但很明显,dbo.Jobs将无法解析为MSSQL中的表名。

我如何在一个项目中对各种数据库进行多次迁移?或者如果我不能,处理这种情况的最好方法是什么?

实体框架中的跨数据库迁移

命令行工具接受-configuration参数来指定配置类,并使用配置类的命名空间来发现/添加迁移。我有两个名称空间:

  • Server.Migrations.MSSQL
    • 配置
    • InitialMigration…
  • Server.Migrations.MySQL
    • 配置
    • InitialMigration…

添加新的迁移:

Add-Migration -configuration Server.Migrations.MSSQL.Configuration MyNewMigration

则在Server.Migrations.MSSQL命名空间下添加一个新的迁移。不幸的是,它总是存储在Migrations/文件夹中,所以你需要手动移动它。

要应用迁移,运行:

Update-Database -configuration Server.Migrations.MSSQL.Configuration

您也可以通过您的代码运行迁移,如:

System.Data.Entity.Migrations.DbMigrationsConfiguration configuration;
switch (ConfigurationManager.AppSettings["DatabaseProvider"].ToUpper())
{
    case "MYSQL":
        configuration = new Migrations.MySQL.Configuration();
        configuration.MigrationsNamespace = "Server.Migrations.MySQL";
        break;
    case "MSSQL":
        configuration = new Migrations.MSSQL.Configuration();
        configuration.MigrationsNamespace = "Server.Migrations.MSSQL";
        break;
    default:
        throw new Exception("Invalid DatabaseProvider, please check your config");
}
configuration.ContextType = typeof(Context);
configuration.MigrationsAssembly = configuration.ContextType.Assembly;
var migrator = new System.Data.Entity.Migrations.DbMigrator(configuration);
migrator.Update();