Search code examples
c#entity-framework-core.net-6.0entity-framework-core-migrations

Can I use EF Core migrations when EF code is spread over multiple solutions?


I'm working on a program that is composed of multiple projects in two different solutions.

We're using dot net 6.0's EF Core as an ORM, but the database was not created using EF, nor the EF model was created from the database (Don't ask me why, it was before I've joined the team).

Anyways, As no one on the team has a lot of experience with EF (including myself), and our team leader wants to know if we can use EF migrations to keep track of database - here's my question to you:

How can we use migrations if our EF code (entities and IEntityTypeConfiguration implementations) are spread over multiple projects in two (or more) solutions?


Solution

  • Turns out the solution was stupidly simple, only had to read a lot and wait for the penny to drop - Here's what I've done at the end (currently as a POC, but I see no reason why it shouldn't work in the larger-scale actual project):

    I've added a new dll project I've called Migrations to the solution that doesn't contain the DbContext class, added to it references of the project where the DbContext exists and references to all the other projects that have entities, and then created in that project a class that inherits the original DbContext of the project, and called it MigrationsDbContext. From that point, All I've had to do was to load all the relevant assemblies from my solution in the constructor of the MigrationsDbContext, and simply run the migrations on that class as my DbContext.

    The benefit is that I only need to change one static property in one class from internal to protected internal for it to work with the real code and that's it.
    The downside is that I'll have to add a reference to every new project with new entities, but that's a really small price to pay for not having to re-write the entire mess.