Entity Framework: Only Seed when building initial database

c# entity-framework entity-framework-6

Question

I'm using Entity Framework 6 with this DbMigrationsConfiguration:

public sealed class Configuration : DbMigrationsConfiguration<DataContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
    }

    protected override void Seed(Danfoss.EnergyEfficiency.Data.DataContext context)
    {
        //Adding initial data to context

        context.SaveChanges();
    }

}

I'm using it in WebAPI in this way:

public static void Register(HttpConfiguration config)
{
    Database.SetInitializer(new MigrateDatabaseToLatestVersion<DataContext, Configuration>());
}

I have noticed that Seed function is running every time my application start up. How can I prevent this? I only like it to run the first time it runs, when it build the initial tables.

1
8
4/23/2015 7:11:01 AM

Popular Answer

The DbMigrationsConfiguration.Seed method is called every time you call Update-Database. The reasoning behind that is explained in this blog by One Unicorn.

That means that you have to write your Seed code to cope with existing data. If you don't like that, you can vote for a change on CodePlex.

In the meantime, to quote the blog:

The best way to handle this is usually to not use AddOrUpdate for every entity, but to instead be more intentional about checking the database for existing data using any mechanisms that are appropriate. For example, Seed might check whether or not one representative entity exists and then branch on that result to either update everything or insert everything

Another option, that I have used in the past, is to add standing data that is related to a migration in the migration itself, using the Sql command. That way it only runs once. I have tended to move away from this because I prefer to keep the seeding in one place.

4
4/23/2015 8:54:01 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow