How to do data migrations inside an EF Core code first migration?

c# entity-framework entity-framework-core

Question

I have a Code First EF Core project.

In my schema migration, I need to do a data migration to an external database. So I can't fall back on migrationBuilder.Sql(). What I need to do is run a query on the local database and insert the data returned into the external database. In other words, I want to do something like this:

// Obviously this is pseudo-code; these interfaces mostly don't exist
protected override void Up(MigrationBuilder migrationBuilder)
{
  var results = migrationBuilder.GetQueryResults("some query");
  using (var extDb = new ExternalDb())
  {
    foreach (var row in results) 
    {
      InsertToExternalDb(row, extDb);
    }
  }
}

But I can't find any method on MigrationBuilder that returns rows from the current database, and I can't even find a way to get the connection string such that I could write a raw ADO query to the current database.

Any other ideas how I could do this?

1
1
8/2/2016 4:24:32 PM

Accepted Answer

The scenario doesn't fall within the capability of migrations for EF Core 1.0.0. The MigrationBuilder API is designed to build SQL for transforming database schema, and isn't designed for working with multiple databases.

You can inspect the implementation of migrations for yourself in EF Core's source code at https://github.com/aspnet/EntityFramework/tree/1.0.0/src/Microsoft.EntityFrameworkCore.Relational/Migrations.

To accomplish a data migration between databases, you'll need to write your own code outside of EF Core migrations.

4
8/2/2016 4:32:02 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow