Where is DbContext.Database.Migrate() method?

Viewed 4388

I'm meant to call this method at startup but it's not reference anywhere:

dbContext.Database.Migrate();

Type DatabaseFacade does not contain a definition for Migrate and no extension method Migrate of type DatabaseFacade could be found (are you missing a using directive or an assembly reference?

So which using / assembly am I missing?

4 Answers

Adding Microsoft.EntityFrameworkCore.SqlServer via NuGet fixed the issue for me.

Just import EntityFrameworkCore by typing the following at the top:

using Microsoft.EntityFrameworkCore;
var migrator = dbContext.Database.GetService<IMigrator>();
await migrator.MigrateAsync("targetMigration", cancellationToken);

(For.Net Core) After adding the package (Oracle/SQLServer) enter image description here

you can design the startup.cs like this using extensions.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app
        .UseSwaggerUI()
        .UseRouting()
        .UseCors(options => options
            .AllowAnyOrigin()
            .AllowAnyHeader()
            .AllowAnyMethod())
        .UseAuthentication()
        .UseAuthorization()
        .UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        })
        .ApplyMigrations();
}

So you can call ApplyMigrations as below.

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

namespace SocialRebate.WebApi.Infrastructure.Extensions
{
    public static class ApplicationBuilderExtensions
    {
        public static IApplicationBuilder UseSwaggerUI(this IApplicationBuilder app)
            => app
                .UseSwagger()
                .UseSwaggerUI(options =>
                {
                    options.SwaggerEndpoint("/swagger/v1/swagger.json", "Your API");
                    options.RoutePrefix = string.Empty;
                });

        public static void ApplyMigrations(this IApplicationBuilder app)
        {
            using var services = app.ApplicationServices.CreateScope();

            var dbContext = services.ServiceProvider.GetService<YourDbContext>();

            dbContext.Database.Migrate();
        }
    }
}
Related