ASP - Core Migrate EF Core SQL DB on Startup

asp.net-core c# entity-framework-core

Question

Is it possible to have my ASP Core Web API ensure the DB is migrated to the latest migration using EF Core? I know this can be done through the command line, but I want to do it programatically.

Update

Based on the answer from Janshair Khan I came up with this helper class:

using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using MyWebApi.Models;

namespace MyWebApi
{
    public static class DataSeeder
    {
        public static void SeedData(this IApplicationBuilder app)
        {
            var context = app.ApplicationServices.GetService<MyContext>();

            if (!context.Database.EnsureCreated())
                context.Database.Migrate();
        }
    }
}

You can call this from the Configure method in your Startup.cs like this:

app.SeedData();
1
53
1/13/2019 2:35:18 PM

Accepted Answer

You can use

db.Database.EnsureCreated();

to get your db up to date with your current model. If you want to enable migrations (If subsequent migrations are suspected), then use

db.Database.Migrate();

and put your subsequent migrations over time.

32
6/14/2016 3:35:16 PM

Popular Answer

A note from documentation on the call to db.Database.EnsureCreated():

Note that this API does not use migrations to create the database. In addition, the database that is created cannot be later updated using migrations. If you are targeting a relational database and using migrations, you can use the DbContext.Database.Migrate() method to ensure the database is created and all migrations are applied.

You may just want to call db.Database.Migrate().

Comment taken from source found above declaration here.



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