How to Work with Multiple Databases in Entity Framework Core Code First

While I was developing a cooperative software for one of our clients. We were requested to use two databases. One for the data other for the logs.

In this project, we used the Code first architecture.

Step 1: we will implement our Entities as an example:

Step 2: Next, we will implement the Database Context class for the Log Database; I have hidden the database name for security reasons. In this project, we used the PostgreSQL open-source database.

(Perfected method) Or you can add the connection string in the appsetting.json like:

If you use the connection string in appsetting.json you need to specify your Dbcontext in startup.cs. In the ConfigureServices Add the following block of code. I have also placed a code for the MSSQL Server.

Step 3: Enable Migrations

Enable-migrations -ContextTypeName LoggerDbContext -MigrationDirectory Migrations.Log Add the migration

Add migration

Add-migration initialMigration -Context LoggerDbContext

Update the Database

Update-database -Context LoggerDbContext


In the Migration directory, you will get

To delete the last migration

Remove-Migration -Context LoggerDbContext

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *