3

I have a migration class:

public partial class TestMigration : Migration
{
    protected override void Up(MigrationBuilder db)
    {

At the end of the Up method, I would like to add some data (seed). MigrationBuilder exposes some methods, also Sql(), but I would like to use EF.

Can I inject DbContext here and do some stuff?

MadDeveloper
  • 796
  • 11
  • 20

2 Answers2

5

I do not recommended you to seed the database in the Migration up or down. this is a bad practice.

You can execute Sql statement in your up/down method and seed the tables as following:

EF6:

public override void Up()
{
    Sql("INSERT INTO Customers (CustomerName, ContactName) VALUES ('Cardinal','Tom B.')");
    ...
}

EF Core 1.0 /7:

protected override void Up(MigrationBuilder db)
{
  db.Sql("INSERT INTO Customers (CustomerName, ContactName) VALUES   ('Cardinal','Tom B.')");
}

where Customer is an entity of the DbSet<'Customer'> Customers by your DbContext

You can create you DbContext during the migration by suppling the connection string or load it from the confiugration but think good about that the database at this time point is not completed and the updating progress still in use. this thing might make for you later really a big troubles.

1) Use the normal DBInitializer.Seed to seed the data to the database.

2) Use the Sql statements in your Migrations Up/Down to transform(update/delete/insert) the data and make the data compatibility between the old database schema and the new one during the migration.

3) Do not try to create DbContext wthing the migration process.

Bassam Alugili
  • 16,345
  • 7
  • 52
  • 70
0

It’s not possible to modify the data during migrations. The current solution for seeding databases is to do that when the application launches, as shown in the Unicode Store sample which ensures that all seed data is available.

There was a discussions on this in issue 3042, the current effort seems to be to change the migration story to make it possible to seed data during a migration. It’s currently planned post-RTM though, so I wouldn’t bet on that for now.

poke
  • 369,085
  • 72
  • 557
  • 602
  • That means each time we run an app, even when there won't be any migrations performed, we will be making dummy 'select from' just to see if given data has to be added. I can imagine that with simple data, but not with anything more complex or with data that user can later e.g. delete... – MadDeveloper May 23 '16 at 07:37
  • Well, it would run when the application is started yes, as a startup cost which does not affect users visiting your sites. And you wouldn’t run this on production servers anyway. Having an automated process there to ensure seed data (outside of a deployment task) is rather uncommon. – poke May 23 '16 at 07:50