Reputation: 23
I'm trying to migrate a database (the database was already created beforehand) through the startup of an ASP.NET Core 3.1 web app. I created the migration by enabling migrations in the Visual Studio Package Manager Console:
enable-migrations
And then created a migration:
Add-Migration TestTable –Context MyDbContext
TestTable
creates a simple table that I use to test the migration.
I want to be able to migrate the database on startup, without the need to use the Visual Studio Package Manager Console, without the need to use the update-database
command.
I have tried this:
var migrationAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
services.AddDbContext<MyDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("MyConnectionString"),
sql => sql.MigrationAssembly(migrationAssembly))));
I get no errors, but the table never gets created. I tried simple crud operations on the table but they throw error because the table doesn't exist, also I checked in the SQL Server Object Explorer and the table isn't there.
Any thoughts will be greatly appreciated.
Best
Upvotes: 2
Views: 2665
Reputation: 74
Take a look at this code
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DataContext dataContext)
{
// migrate any database changes on startup (includes initial db creation)
dataContext.Database.Migrate();
...
}
here's the reference link: https://jasonwatmore.com/post/2019/12/27/aspnet-core-automatic-ef-core-migrations-to-sql-database-on-startup
Upvotes: 2