Shaul Behr
Shaul Behr

Reputation: 38033

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

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?

Upvotes: 1

Views: 1742

Answers (1)

natemcmaster
natemcmaster

Reputation: 26813

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.

Upvotes: 4

Related Questions