Database initialization in asp.net mvc core 2

entity-framework-core

Question

I have created a very basic web application with asp.net mvc core 2.

This application works with a Database and entity framework core. I have worked with Migration and Code First stragegy.

Everything works fine.

I can create the database with command:

$ dotnet ef database update

What i want to do at this time is to create some data in the database (from C# code).

I have read some tutorials and i created a DataInitializer class which contains code that will create my data.

I have put this line at the end of Startup.cs Configure method:

    DataInitializer dataseed = new DataInitializer();
    dataseed.InitializeDataAsync(app.ApplicationServices);

The problem is that data is inserted each time i run my application.

I do not want to check by C# code if data is even in the database because it is very dangerous.

What i want to do is to trigger data initialization with migration. Is it possible ?

Thanks

1
0
12/3/2017 8:53:33 AM

Popular Answer

this is the format I use for running seed data into a fresh table it works only runs 1 time per table assuming no data in that table.

 //run migrations 
_context.Database.Migrate();

if(!_context.SomeTable.Any()){
   //foreach 
     //insert
  _context.SaveChanges();
}
0
12/3/2017 8:02:33 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow