【问题标题】:Cross Database Migrations in Entity Framework实体框架中的跨数据库迁移
【发布时间】:2014-08-04 15:20:08
【问题描述】:

我希望我的应用程序能够使用各种数据库,例如 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 以外的任何其他表名。

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

【问题讨论】:

  • 只要有一个名为“dbo”的模式,相当多的 RDBMS 将识别“dbo.jobs”。也许您的架构名称需要是动态的。也许您需要一个可靠地存在于每个可能的目标数据库上的所有者/模式。

标签: c# sql .net sql-server entity-framework


【解决方案1】:

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

  • Server.Migrations.MSSQL
    • 配置
    • 初始迁移 ...
  • Server.Migrations.MySQL
    • 配置
    • 初始迁移 ...

添加新迁移:

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();

【讨论】:

    猜你喜欢
    • 2014-07-08
    • 1970-01-01
    • 1970-01-01
    • 2019-06-24
    • 1970-01-01
    • 2012-10-14
    • 2021-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多