Base solution for your next web application
Starts in:
01 DAYS
01 HRS
01 MIN
01 SEC
Open Closed

Multiple DB Context - Unable to Implement #856


User avatar
0
maharatha created

Hi All -

I am trying to connect to another database from my application and get some values from multiple tables. I am trying to use a secondary DB context for which I have declared a connection string as

<add name="Second" connectionString="Server=myserverinstance; Database=myseconddb; Trusted_Connection=True;" providerName="System.Data.SqlClient" />

Then trying to use the code to connect like the below :

using (var context = new ONLINEDOCDbContext("Second")) { context. <<this gives me the list of tables from the first database instead of my seocnd database>>

        }

Am I doing something wrong here ?

Please guide.

The whole idea is to access multiple database using different DB context. Please provide an implmenetation.

Thanks for your wonderful support so far.


1 Answer(s)
  • User Avatar
    0
    hikalkan created
    Support Team

    Hi,

    First of all; creating a new dbcontext (new ONLINEDOCDbContext) is not a good approach. Because, we should use dependency injection.

    I have implemented multiple dbcontext before. You can check this sample: <a class="postlink" href="https://github.com/aspnetboilerplate/aspnetboilerplate-samples/tree/master/MultipleDbContextDemo">https://github.com/aspnetboilerplate/as ... ontextDemo</a>

    Does your second dbcontext inherits from AbpZeroDbContext or AbpDbContext? If you don't need base entities, just derive from AbpDbContext. Example: <a class="postlink" href="https://github.com/aspnetboilerplate/aspnetboilerplate-samples/blob/master/MultipleDbContextDemo/MultipleDbContextDemo.EntityFramework/EntityFramework/MySecondDbContext.cs">https://github.com/aspnetboilerplate/as ... Context.cs</a>

    Then you can inject IRepository<YourEntityInSecondDbContext> wherever you need. Do not directly use DbContexes, use repositories.