【问题标题】:Entity Framework code first migrations for two different databases实体框架代码首先迁移两个不同的数据库
【发布时间】:2017-12-28 07:40:33
【问题描述】:

我对这里的情况感到很困惑。我需要连接两个独立的数据库,一个是 SQL Server 数据库,另一个是 MySQL 数据库。

我在web.config 文件中有连接字符串。我能够连接到服务器并访问数据。

但是,我需要同时在两台服务器上运行实体迁移。或者一个一个,我觉得是不可能的。

这是我的数据库上下文:

// Database 1
public class DatabaseContext : DbContext
{
    public DatabaseContext() : base("name=OldDBContext"){ }

    protected override void OnModelCreating(DbModelBuilder modelBuilder) { }

    public static DatabaseContext Create()
    {
        return new DatabaseContext();
    }

    public DbSet<User> UserModel { get; set; }
}

// Database 2
public class NewDatabaseContext : DbContext
{
    public NewDatabaseContext() : base("name=NewDBContext") { }

    protected override void OnModelCreating(DbModelBuilder modelBuilder) { }

    public static NewDatabaseContext Create()
    {
        return new NewDatabaseContext();
    }

    public DbSet<UserData> UserDataModel { get; set; }
}

最初我只有一个数据库,我曾经在包管理器控制台中运行add-migration MigrationName,它会使用数据库中的更改创建一个迁移。

但是现在,当我有两个独立的数据库时,迁移不包含第二个数据库或我后来添加的数据库中的任何更改。

请帮忙。非常感谢任何帮助。

谢谢

【问题讨论】:

  • 如何在启动文件中注册两个 DbContext?另外,您是否希望两个数据库在数据更改时都更新?
  • @KidCode 我没有在 global.asax 中注册任何数据库。当我只有一个数据库时,我想没有必要。
  • @KidCode 我想像update-databaseadd-migration 一样更新数据库架构,但只有一个数据库正在更新。

标签: c# entity-framework ef-code-first entity-framework-6 entity-framework-migrations


【解决方案1】:

尝试为第二个上下文启用迁移,使用 ContextTypeName 参数

Enable-Migrations -EnableAutomaticMigrations -ContextTypeName
NamespaceOfContext.NewDatabaseContext 

它将创建单独的配置。如果发生命名冲突重命名 Migrations 文件夹中的配置文件,那么您可以针对特定配置运行数据库更新

Update-Database -ConfigurationTypeName ConfigurationName

【讨论】:

猜你喜欢
  • 2014-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-05
  • 2015-11-06
  • 2013-12-29
相关资源
最近更新 更多