This one was somewhat hard to find because all examples use the command line, so documenting here.

Suppose you want to build a core application and use EF core for the backend, all code first of course.

This is all covered in the walkthroughs but hack, for reference:

Add the dependencies to EF in the project.json:

"Microsoft.EntityFrameworkCore.SqlServer": "1.0.1", "Microsoft.EntityFrameworkCore.Design": "1.0.0-preview2-final"

And to the tools section:

"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"

Add the context in the ConfigureServices part:

var connection = @"Server=(localdb)\mssqllocaldb;Database=NewDb;Trusted_Connection=True;"; services.AddDbContext<Model.MyContext>(options => options.UseSqlServer(connection));

And to satisfy the EF command line tools add this constructor to your context:

public MyContext(DbContextOptions<MyContext> options) : base(options) { }

Now you will be able to fire the EF command to create the first migration:

dotnet ef migrations add myfirst

And now the important part. Of course you want your program to run the migration (and subsequent ones) automatically upon application startup. In the EF 6.x days this could be done by using the MigrateDatabaseToLatestVersion database initializer.

This changed in EF core. Now you will have to use:


What I have done is added my context the the configure method in startup.cs:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, MyContext context) { context.Database.Migrate(); ....

The context will be injected here and your database will be migrated to the lastest version. There you go..