Best way to incrementally seed data in Entity Framework 4.3

If you want to use entities to seed data you should use Seed method in your migrations configuration. If you generate fresh project Enable-Migrations you will get this configuration class:

internal sealed class Configuration : DbMigrationsConfiguration<YourContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
    }

    protected override void Seed(CFMigrationsWithNoMagic.BlogContext context)
    {
        //  This method will be called after migrating to the latest version.

        //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
        //  to avoid creating duplicate seed data. E.g.
        //
        //    context.People.AddOrUpdate(
        //      p => p.FullName,
        //      new Person { FullName = "Andrew Peters" },
        //      new Person { FullName = "Brice Lambson" },
        //      new Person { FullName = "Rowan Miller" }
        //    );
        //
    }
}

The way how migrations seed data are not very efficient because it is supposed to be used for some very basic seeding. Every update to new version will go through whole set and try to update existing data or insert new data. If you don’t use AddOrUpdate extension method you must manually ensure that data are seeded to database only if they are not present yet.

If you want efficient way for seeding because you must seed o lot of data you will get better result with common:

public partial class SomeMigration : DbMigration
{
    public override void Up()
    {
        ...
        Sql("UPDATE ...");
        Sql("INSERT ...");
    }

    public override void Down()
    {
        ...
    }
}

Leave a Comment