Entity Framework Seeding Data during migrations


Example

After enabling and creating migrations there might be a need to initially fill or migrate data in your database. There are several possibilities but for simple migrations you can use the method 'Seed()' in the file Configuration created after calling enable-migrations.

The Seed() function retrieves a database context as it's only parameter and you are able to perform EF operations inside this function:

protected override void Seed(Model.DatabaseContext context);

You can perform all types of activities inside Seed(). In case of any failure the complete transaction (even the applied patches) are being rolled back.

An example function that creates data only if a table is empty might look like this:

protected override void Seed(Model.DatabaseContext context)
{
    if (!context.Customers.Any()) {
        Customer c = new Customer{ Id = 1, Name = "Demo" };
        context.Customers.Add(c);
        context.SaveData();
    }
}

A nice feature provided by the EF developers is the extension method AddOrUpdate(). This method allows to update data based on the primary key or to insert data if it does not exist already (the example is taken from the generated source code of Configuration.cs):

protected override void Seed(Model.DatabaseContext context)
{
    context.People.AddOrUpdate(
      p => p.FullName,
      new Person { FullName = "Andrew Peters" },
      new Person { FullName = "Brice Lambson" },
      new Person { FullName = "Rowan Miller" }
    );
}

Please be aware that Seed() is called after the last patch has been applied. If you need to migration or seed data during patches, other approaches need to be used.