0

How to create two different database context to use two different database in EF core. i am using database first approach.

Currently using the following line to use in my startup.cs

builderModel.Services.AddDbContext<DB1Context>(options =>
            options.UseSqlServer(configuration.GetConnectionString("DB1Context")));

Thanks

2
  • 2
    What's keeping you from doing the same thing you did for DB1Context and just name it DB2Context?
    – nvoigt
    Feb 24, 2020 at 13:41
  • Are you getting any errors doing the obvious (copy and inherit)? Feb 24, 2020 at 13:57

2 Answers 2

2

Sounds pretty straight forward (if DBs are already set up and equal in schema). Try

builderModel.Services.AddDbContext<DB1Context>(options =>
            options.UseSqlServer(configuration.GetConnectionString("DB1Context")));

builderModel.Services.AddDbContext<DB2Context>(options =>
            options.UseSqlServer(configuration.GetConnectionString("DB2Context")));

And as a bonus, you can inherit from the existing DbContext you already have (because it's the same code).

0

so if i understand you correctly: with your "Startup-Line" you add the first (DB1Context) Context to the "program", if you have 2 DbContexts you obviously need 2 of these (same for DB2).

now you can migrate it by using the nuget-package-console(google it if you never heared of it^^) and write : Add-migration mymigration -context:Db1Context Add-migration mymigration -context:Db2Context

*Mymigration is the name of the *.cs(in this case: Mymigration.cs) file which is used for the creation/update of the database, you could also give it a different name. it also creates a folder calles "migration" where the *.cs file is stored

After that you have to update your database with the comment:

update-database

Than you should have 2(or at least 2 upgraded) new Tables in your Database.

IF add migrtion doesnt work, make shure you picked the correct Project (where the contexts are located)

I aslo have to admit that i never tried to migrate 2 Contexts, but in theory thats the way to do it.... This is my first answer on Stackoverflow so i hope i could help you :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.