I am trying to apply migrations programmatically using Entity Framework Core 2.0, in a Code-First ASP.Net Core 2.0 project. If I run the migrations manually through a terminal, they're applied without issue. Applying the migrations in my Startup
class though results in the database model never changing.
Am I doing this wrong?
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddEntityFrameworkSqlite();
services.AddDbContext<ApplicationContext>(options => options.UseSqlite("Data Source=blogging.db"));
services.AddDbContext<UserContext>(options => options.UseSqlite("Data Source=blogging.db"));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
var services = app.ApplicationServices.GetService<IServiceScopeFactory>();
var context = services.CreateScope().ServiceProvider.GetRequiredService<ApplicationContext>();
context.Database.Migrate();
}
I can run this from the terminal and it works fine:
dotnet ef migrations add FourthMigration --context EFCore_Test.DataAccess.ApplicationContext
I have multiple DataContext
Types; only one represents the entire data model and the rest are used just to access the database in a more domain specific manor. The ApplicationContext
represents my "everything + kitchen sink" data context. It's this context that I perform my migrations and updates with.
In preparation for deploying to Azure, I want to have the web-app migrate itself with each deployment, instead of having to wire up powershell scripts to run the dotnet core tooling commands.
The new Migration files aren't picked up and added to the solution explorer in Visual Studio for macOS. I originally didn't think anything of this because I assumed the IDE was using dotnet build
under the hood, which would pick up the migration files. I'm not sure what the IDE does, but when I build with those migration files missing, they're not included in the compiled assembly. This would cause the app to never migrate on startup.
I manually added the migration classes in the Solution Explorer, then ran the app and the migration was applied. I repeated this several times with multiple migrations and never had another issue.