ASP - Core Migrate EF Core SQL DB on Startup

后端 未结 11 947
故里飘歌
故里飘歌 2020-12-01 02:32

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

11条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 03:26

    This works for me in ASP.NET Core 3.1, simply injecting the db context as a parameter to the Configure method after registering it in the ConfigureServices method.

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext(x => x.UseSqlite("Data Source=LocalDatabase.db"));
    
        ...
    }
    
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DataContext dataContext)
    {
        dataContext.Database.Migrate();
    
        ...
    }
    

    More details and links to full code samples available at https://jasonwatmore.com/post/2019/12/27/aspnet-core-automatic-ef-core-migrations-to-sql-database-on-startup

提交回复
热议问题