Wes Duff Wes Duff - 3 months ago 38
ASP.NET (C#) Question

ASP.net CORE : How to execute a migration on project start

I am looking to execute a migration command inside the start.cs file.
So when the application first runs, it looks for the database and if it does not exist then it runs the migration scripts.

I know you can do this in the package manager console with "dotnet migrations" but I am looking to do this through code.

Thanks!




UPDATE



Looks like this worked for me




  • Inside my Startup.cs file, inside the Startup constructor method.

    using (
    var context = new PeopleContext(
    _config,
    new Microsoft.EntityFrameworkCore.DbContextOptions<PeopleContext>()
    ))
    {
    context.Database.EnsureCreated();
    }

  • I am using a "using" statement here to make sure my DbContext gets closed when I am done with it.

  • After I create my context I then call its method to make sure the DataBase is there, if not then I add the dataBase and run migrations.



I am using ASP.NET Core : NETStandard, Version=v1.6

Pretty much the latest greates as of 9/1/2016




Update 2



Looks like using the .Migrate() method may be the way to go.

Note *



To use .Migrate() you will need to add

using Microsoft.EntityFrameworkCore;


Here is what I am using now.

using (var context = new PeopleContext(_config,new Microsoft.EntityFrameworkCore.DbContextOptions<PeopleContext>()))
{
//context.Database.EnsureCreated();
context.Database.Migrate();
}

Answer

To run EF7 Migrations on application startup for .Net Core, I have:

in ConfigureServices()

using (var dataContext = (DataContext)app.ApplicationServices.GetService(typeof(DataContext)))
            {
                dataContext.Database.Migrate();
            }

This runs the new migrations on startup.

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