Andrew Connell
Andrew Connell

Reputation: 5287

EF5 Code First Migrations - DB Init running over and over

Got this weird thing going on with my new EF5 Code First app that's leveraging new new migrations support. One thing that I'm seeing is that the database seeding routine is running on the initial DB load, but what's strange is that it seems to run again after the app hasn't run in a while. Is this to be expected? What's the best way to keep this from happening?

I get the whole .AddOrUpdate(), but still seems odd to have this run more than when the app first ran and created the DB schema. Ideas?

Upvotes: 2

Views: 579

Answers (2)

Tallmaris
Tallmaris

Reputation: 7590

My understanding is that having AutomaticMigrationsEnabled set to true in the Configuration, will trigger migrations every time the App Start (that is probably why you see that behaviour when the app has not run for a while).

Problem is that then the Migrations code will run the seed even if there was nothing to migrate. I would use a solution similar to @OdeToCode but I would rather have my check done using the DB itself (something like test if the table is empty etc. etc.)

Indeed, the new Enable-Migrations command will set the AutomaticMigrationsEnabled to false in the generated Configuration.cs file.

Initializers are indeed another form of setting up the DB and as you rightly say they are more useful in a testing/prototyping context that allows you to reset the DB to a known state each time. It looks like duplicated functionality but with different purposes: in a production DB I would not use one of the pre-baked Initializers.

Upvotes: 0

OdeToCode
OdeToCode

Reputation: 4986

Yes, that is the expected behavior. The Seed method runs even when there are no schema changes to apply.

If you have a heavy amount of work going on in the Seed method and want more control, you could do something like add an app setting to the project's .config file:

<appSettings>
    <add key="seedDatabase" value="true"/>
</appSettings>

Then check for the setting in the Seed method.

protected override void Seed(BarDb context)
{
    if(ConfigurationManager.AppSettings["seedDatabase"] == "true")
    {
        // ... seed logic
    }            
}

Upvotes: 2

Related Questions