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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With