abp icon indicating copy to clipboard operation
abp copied to clipboard

Multiple databases, one module - how do I do it? Mulitple contexts?

Open tinonetic opened this issue 6 years ago • 5 comments

Hi,

What do I do if I have one module that needs to access 3 different databases.

Creating additional contexts does not seem to work.

When I run the migrator, it fails with an error: Invalid object name 'AbpUsers'

I have read through:

  1. https://docs.abp.io/en/abp/master/Entity-Framework-Core-Migrations
  2. https://docs.abp.io/en/abp/latest/Multi-Tenancy (I do not want multi-tenancy)

The closest I came to a possible answer is at https://docs.abp.io/en/abp/master/Connection-Strings#database-migrations-for-the-entity-framework-core, but I do not understand it

Thank-you!

tinonetic avatar Jun 08 '20 10:06 tinonetic

What do I do if I have one module that needs to access 3 different databases.

Can you explain the use case in detail?

maliming avatar Jun 09 '20 08:06 maliming

Hi @maliming ,

Thanks for responding. Sorry for the late reply. I have now managed to make it work, but would still need guidance if it is good practice

I have a single module which needs to access 3 different databases.

In the _MyCompany.Project._EntityFrameworkCore, I have 3 different DbContexts of type AbpDbContext<MyDbContext>, IMyDbContext

Each has a relevant [ConnectionStringName()] attribute

The difference between my additinal DbContexts and the one generated by the ABP template is that they just have the constructor

In the _MyCompany.Project._EntityFrameworkCoreModule, I then add the additional contexts in public override void ConfigureServices(ServiceConfigurationContext context) method

It now works.

Question is, is this the recommended practice?

tinonetic avatar Jun 11 '20 10:06 tinonetic

I think that's a good implementation: Create one DbContext for each database you want to connect with different ConnectionStringName attributes. If target databases have necessary tables then it will work as expected.

hikalkan avatar Jun 14 '20 16:06 hikalkan

Thank-you

tinonetic avatar Jun 15 '20 14:06 tinonetic

Very useful... thanks for sharing. I did the same thing.

aelhadi avatar Oct 31 '20 12:10 aelhadi