'Where is DbContext.Database.Migrate() method?

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?



Solution 1:[1]

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

Solution 2:[2]

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

Solution 3:[3]

(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();
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hamed
Solution 2 Matthew Hostetler
Solution 3 Andronicus