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

时间:2014-08-04 15:20:09

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

我希望我的应用程序可以使用各种数据库,如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);
        // ....
    }
}

但很显然,除了MSSQL之外,dbo.Jobs无法解析为表名。

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

1 个答案:

答案 0 :(得分:0)

命令行工具接受-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();