Entity Framework Core: create a migration that merges multiple DbContexts (with multiple migrations)

c# entity-framework-core entity-framework-core-2.2 entity-framework-core-migrations identityserver4

Question

When I started a project (an Identity Server 4 server) I created an ApplicationDBContext (which inherits from ASP.NET IdentityContext and hassome custom tables) and used the ConfigurationDBContext as well as the PersistedGrantDBContext from Identity Server 4. I created 3 migrations (one for each DBContext). Though the data is in the same database (so a single database).

Now I refactored my code giving me a new DBContext having all 3 databases in one DBContext.

My problem is the new migration.

So far I deleted the old DBContexts and created a migration that creates the exact same database again when I run it against an empty database.

But when it comes to migrate an existing database (with existing data) it raises the exception that table X already exists.

I assume this is because I have deleted the old code and the old migrations.

So, how can I create a migration that merges 3 different DBContexts into a single new DBContext.

I assume if I leave the old code in place and use the old migrations too it tries to create the tables multiple times (since they are in the old splitted migrations and the new combined migration)?

Is there a way to tell the new migration to not throw an error if the table exists (and take the table as it is since it is the same layout).

1
0
5/15/2019 2:04:01 PM

Popular Answer

In my opinion, you have to keep 3 default(old) contexts.

Because: It's a very bad practice to merge 3 in 1 and retire their default contexts.

  1. all those 3 contexts have their APIs to play with their data, which APIs will make sure all data is well maintained and which APIs will make Code-First is real code-first, but not a Code-Once.
  2. if you merge them to one, how would you keep Database&APIs up-to-date with those projects? and how would you implement those APIs, you want to write them again?
  3. Code-First is designed mainly for database changes, if you do need to custom them, just customize them in their own context. then you can use your own context to combine them to one, but unfortunately, you have to carefully maintain your migration code to make sure no conflicts with each other.
  4. I suggest you use IdentityContext as base for your new context and don't merge the other 2 to here. which you can keep 3 contexts.
0
5/15/2019 2:23:49 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow