3

Ist es möglich, StartUp.cs oder project.json zu konfigurieren, um Datenbankmigrationen mit Entity Framework Core beim Start der Anwendung auszuführen?Datenbankmigrationen mit Entity Framework Core beim Start der Anwendung ausführen

Nun habe ich Middleware, die diese Aufgabe zu tun, aber es scheint negativen Einfluss auf die Leistung, weil die Datenbank wird jede Anfrage erhalten geprüft.

public class EntityFrameworkUpdateDatabaseMiddleware 
{ 
    private readonly RequestDelegate _next; 
    private readonly ApplicationDbContext _dbContext; 

    public EntityFrameworkUpdateDatabaseMiddleware(RequestDelegate next, ApplicationDbContext dbContext) 
    { 
     _next = next; 
     _dbContext = dbContext; 
    } 

    public async Task Invoke(HttpContext context) 
    { 
     await _dbContext.Database.MigrateAsync(); 
     await _next.Invoke(context); 
    } 
} 

Antwort

7

Sie können dies in den Konfigurationsmethoden in Ihrem Startup.cs. Der einfachste Weg ist wie folgt:

public void ConfigureServices(IServiceCollection services) 
{ 
    services.AddDbContext<ApplicationDbContext>(); 

    // add other services   
} 

public void Configure(IApplicationBuilder app, ApplicationDbContext db) 
{ 
    db.Database.Migrate(); 

    // configure other services 
}