Doug
Doug

Reputation: 6518

EF 4.3 Code First Migrations - Seed per migration

have recently started using Code First Migrations and was wanting to seed data in each Up method.

is this possible?

Ie.

  1. Create database table
  2. Fill with data

for Drop:

  1. Delete data from joining table
  2. delete table

Upvotes: 2

Views: 720

Answers (2)

fduzceker
fduzceker

Reputation: 31

public partial class DBInitializer : IDatabaseInitializer<DBContext>
{
    public void InitializeDatabase(DBContext context)
    {

        var cfg = new Migrations.Configuration();
        var migrator = new DbMigrator(cfg);

        List<string> pendingMigrations = new List<string>(migrator.GetPendingMigrations());

        foreach (string migration in pendingMigrations)
        {
            Console.WriteLine("Updating Migration:" + migration);
            migrator.Update(migration);
            Console.WriteLine("Updated Migration:" + migration);

            if (migration.Contains("AddMyProperty"))
            {
                // seed data codes
                context.SaveChanges();
            }                
        }

    }

}

Upvotes: 3

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364389

Yes it is possible but you must do it through executing SQL commands. Use Sql method in both Up and Down methods of your migration to execute INSERT and DELETE SQL commands.

Upvotes: 6

Related Questions