Roman Pokrovskij
Roman Pokrovskij

Reputation: 9776

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

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.

Upvotes: 5

Views: 1778

Answers (1)

Kevin Fichter
Kevin Fichter

Reputation: 1067

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))
            .BuildServiceProvider();

        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);

        Console.ReadKey();

    }
}

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):

Migration:

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

Database Update:

dotnet ef database update --context AnimalContext

Upvotes: 3

Related Questions