Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework: Only Seed when building initial database

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.

like image 695
dhrm Avatar asked Apr 23 '15 07:04

dhrm


1 Answers

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.

like image 127
Colin Avatar answered Oct 22 '22 06:10

Colin