-2

I am using migrations and also want to use seed data. Currently getting error. what is the best way to achieve this?

My earlier query in stackoverflow: previous post

Thanks

Mukil Deepthi
  • 6,072
  • 13
  • 71
  • 156
  • *Currently getting error*... so what is the error? And how would you expect migrations and seeding to work if they ran in parallel? That would almost certainly break things. – DavidG Nov 23 '17 at 14:22

1 Answers1

0

For what ever its worth migrations do not run with EnsureCreatedAsync, its in real big bold letters in the docs for EFCore, also to get around this Run EnsureDeletedAsync with in your seed method (testing anyway right?). Then run Database.MigrateAsync();

https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/#applying-migrations-at-runtime

so....

Edit

//example method
public void Seed(IApplicationBuilder app)
{
     using(var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
     {
        var context = servicescope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
        context.Database.Migrate();
         if(!context.SomeTable.Any()){
            foreach(var item in SeedData.Items){
              context.SomeTable.Add(item);
            }
            context.SaveChanges();
         }

        //for each table you need seeded data...
        //...
     }
}
mvermef
  • 3,814
  • 1
  • 23
  • 36
  • Thanks. I dont want the database to get deleted if one exists. I want this seed to run only when migrate to new database. – Mukil Deepthi Nov 29 '17 at 14:17
  • Then don't run the delete method but the migrate call is the only way without running commands on command line to get migrations. If it's a new dB then check using `if(!_context.SomeTable.Any()) ` loop thru seed data, for example – mvermef Nov 29 '17 at 15:03
  • Using if(!_context. SomeTable.Any()) will invoked when all the migration scripts are executed? What i understand is from pmc -> update-database is executed, all migrations will be applied to new database, and the seed data is called. is that righ? – Mukil Deepthi Nov 29 '17 at 15:05
  • Yes this is assuming no data, i.e. new database. Seed only needs to run once but migrations will run if one exists. Add new table then add more !Any() if logic to seed that new table if necessary. – mvermef Nov 29 '17 at 15:12
  • edited for example. – mvermef Nov 29 '17 at 20:11