Entity Framework: only seed when creating source database

I am 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 use it in WebAPI as follows:

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

I noticed that the Seed function runs every time my application starts. How can I prevent this? I just like to run it on the first start, when it creates the source tables.

+5
source share
1 answer

The DbMigrationsConfiguration.Seed method DbMigrationsConfiguration.Seed called every time you call Update-Database . The rationale for this is explained in this One Unicorn blog.

This means that you need to write your Seed code to handle existing data. If you do not like this, you can vote for the CodePlex change.

In the meantime, to quote the blog:

The best way to handle this is usually not to use AddOrUpdate for each object, but instead there should be a more intentional database for existing data using any suitable mechanisms. For example, a seed can check if one representative exists and then branches onto this result to either update everything or insert everything

Another option I've used in the past is to add persistent data related to the migration in the migration itself using the Sql command. Thus, it works only once. I tend to move away from this because I prefer to keep sowing in one place.

+4
source

All Articles