Wes Duff Wes Duff - 1 year ago 411
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.



Looks like this worked for me

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

    using (
    var context = new PeopleContext(
    new Microsoft.EntityFrameworkCore.DbContextOptions<PeopleContext>()

  • 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>()))

Answer Source

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

in ConfigureServices()

using (var dataContext = (DataContext)app.ApplicationServices.GetService(typeof(DataContext)))

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/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download