c# - How to execute a migration on project start -


i looking execute migration command inside start.cs file. when application first runs, looks database , if not exist runs migration scripts.

i know can in package manager console "dotnet migrations" looking through code.

thanks!


update

looks worked me

  • inside startup.cs file, inside startup constructor method.

       using (         var context = new peoplecontext(             _config,             new microsoft.entityframeworkcore.dbcontextoptions<peoplecontext>()         ))     {         context.database.ensurecreated();     } 
  • i using "using" statement here make sure dbcontext gets closed when done it.

  • after create context call method make sure database there, if not add database , run migrations.

i using asp.net core : netstandard, version=v1.6

pretty latest greates of 9/1/2016


update 2

looks using .migrate() method may way go.

note *

to use .migrate() need add

using microsoft.entityframeworkcore; 

here using now.

        using (var context = new peoplecontext(_config,new microsoft.entityframeworkcore.dbcontextoptions<peoplecontext>()))         {             try             {                 context.person.any();             }             catch (exception ex)             {                 //context.database.ensurecreated();                 context.database.migrate();             }          } 

to run ef7 migrations on application startup .net core, have:

in configureservices()

using (var datacontext = (datacontext)app.applicationservices.getservice(typeof(datacontext)))             {                 datacontext.database.migrate();             } 

this runs new migrations on startup.

i not sure ensurecreated run new migrations after initial table creation? see: http://thedatafarm.com/data-access/ef7-ensurecreated-vs-migrate-methods/


Comments