EF CORE: is it possible to support two models in one database?

ef-migrations entity-framework entity-framework-core entity-framework-core-2.1


Is it possible to support two different EF Core models with all "migrations functionality" in one database?

I guess I should somehow separate dbo._EFMigrationsHistory ? Can't find such option in documentation.

11/8/2018 3:35:59 PM

Accepted Answer

Yes, you can have multiple contexts within the same database. I've put together a sample showing three contexts in the same database. You declare three contexts as you usually would, and the differences manifest themselves when you setup migrations; you just need to be more explicit here, naming the context you're migrating or updating, and it is a good idea to also be explicit about where the migration is going.

Here's the Program.Main of the sample project linked above, showing a basic addition of three contexts for dependency injection, then doing "stuff" with each. See the repo on Github for the rest of the files.

    class Program
    static async Task Main(string[] args)
        var providers = new ServiceCollection()
            .AddDbContext<AnimalContext>(options => options.UseSqlServer(Globals.CONNECTIONSTRING))
            .AddDbContext<DoctorContext>(options => options.UseSqlServer(Globals.CONNECTIONSTRING))
            .AddDbContext<CarContext>(options => options.UseSqlServer(Globals.CONNECTIONSTRING))

        var animalContext = providers.GetService<AnimalContext>();
        await AnimalHelpers.Seed(animalContext);
        await AnimalHelpers.Read(animalContext);

        var carContext = providers.GetService<CarContext>();
        await CarHelpers.Seed(carContext);
        await CarHelpers.Read(carContext);

        var doctorContext = providers.GetService<DoctorContext>();
        await DoctorHelpers.Seed(doctorContext);
        await DoctorHelpers.Read(doctorContext);



To initialize the database, I ran a migration for each context, then ran update database for each, as follows (in powershell; PMC commands/flags differ slightly):


dotnet ef migrations add CreateAnimalsSchema --context AnimalContext -o Data/Migrations/Animals

Database Update:

dotnet ef database update --context AnimalContext

7/2/2018 1:58:07 PM

Related Questions


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