0

I'm looking for any way to generate and run EF Core migrations on app startup/at runtime. I'm developing in a docker container, so I do not have the luxury of using the migrations cli when my schema changes I want to check if the current database lines up with my schema, generate and run the migrations if not, and carry on, without having to completely recreate the database if it exists (EnsureDeleted/EnsureCreated).

Essentially, I'm looking for a way to call dotnet ef migrations add <migration name> and dotnet ef migrations update in my C# code (in the Startup.Configure method, if possible), if the schema in code does not line up with the database schema. I've seen the Migrate method, but that only applies pending migrations, it does not generate anything. And I cannot use EnsureDeleted and EnsureCreated because they would remove the entire database, even if there is some preexisting data.

I'm using .Net 6 with an ASP.Net Web Api project, if it helps.

kaptcha
  • 68
  • 2
  • 10
  • Have you looked at https://www.entityframeworktutorial.net/code-first/migration-in-code-first.aspx – iSR5 Mar 15 '22 at 18:46
  • @iSR5 That article is for EF6, which was originally released in 2013. I'm using EF Core. Their APIs are fundamentally different, so I cannot use it. – kaptcha Mar 15 '22 at 18:57
  • Sorry, this one https://stackoverflow.com/questions/39526595/entityframework-core-automatic-migrations – iSR5 Mar 15 '22 at 19:01
  • I just looked, it doesn't seem to be working for me. – kaptcha Mar 15 '22 at 19:29
  • You can apply migrations at runtime, but you cannot create them (because adding migrations require modifying the migrations assembly project and building it). EF6 runtime automatic migrations are gone (retired) in EF Core. – Ivan Stoev Mar 15 '22 at 19:36
  • The author of [this post](https://stackoverflow.com/a/61415487/5202563) claims to have created a package called [EFCore.AutomaticMigrations](https://www.nuget.org/packages/EFCore.AutomaticMigrations/) addressing your issue. But I haven't tried it and also I don't see source code, so you may try it on your own risk. – Ivan Stoev Mar 15 '22 at 19:47
  • 1
    @IvanStoev That is what I tried, it seems like it would have worked, but it was built for SQL Server. I'm using Postgres, so it's not compatible. Thanks anyways! – kaptcha Mar 15 '22 at 20:01

0 Answers0