Multiple instances of the same DbContext with different connection strings

See original GitHub issue

I know this is more like a howto question and should be asked on StackOverflow. I did ask here: https://stackoverflow.com/questions/45724257/asp-net-core-with-separate-databases but it seems like there are not too many experts being able to answer this. Maybe someone here can help.

My ASP.NET Core 2.0 application must support multiple databases. Which database is to be used should depend on the ApplicationUser issuing a request on a per-request basis.

That rules out AddDbContext in Startup.cs with a single connection string (there will be multiple connection strings in my application.json file).

A multi-tenant approach as described here http://benfoster.io/blog/asp-net-5-multitenancy seems to be too restrictive because I actually don’t want complete isolation. There will be users (managers etc.) that should be able to switch between databases. Normal users will be restricted to one specific database. Apart from that I thought I could manage this without third party code.

I found this https://github.com/aspnet/EntityFrameworkCore/issues/6863 which seems to be related.

Note: I don’t need multiple instances of the same context in my controller, as discussed here https://github.com/aspnet/DependencyInjection/issues/352 I just need the correct one depending on the user.

In my SO post ‘poke’ comments:

Database contexts are usually configured to be created once per every request, so the configuration can change on a per-request basis. You just need to come up with a nice way to configure the contexts depending on your user … So you should use a single database context but just make sure that your DbContextOptions configure the correct connection string per request. Or put the logic inside the db context (ugh though) by overriding OnConfiguring

So how do I use DbContextOptions to realize this?

I would be thankful for every hint!

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

14reactions
ajcvickerscommented, Aug 30, 2017

@nicolasr75 Assuming you are using EF Core 2.0, then you can put logic into the code that builds the options. For example:

services.AddDbContext<MyDbContext>((serviceProvider, builder) =>
{
    // Use some code here to look up the connection string
    // Note that the service provider (serviceProvider) is available if needed
    var connectionString = ...;
    builder.UseSqlServer(connectionString);
});

The options are now registered as scoped by default, so this code will run once each request to determine the connection string to use.

You could also put similar code into OnConfiguring if you prefer that pattern.

4reactions
eduardomarcommented, Jul 25, 2018

@ajcvickers There way to get a route attribute([Route(“api/{CompanyCode}/[controller]”)]) in this code?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Entity Framework Core multiple connection strings on ...
Connection string can be resolved using IServiceProvider . In the example below I map query parameter to configuration from appsettings.json , ...
Read more >
How to implement multiple Connection Strings for one ...
Essentially, you just need to have 2 Database Context classes inheriting your primary Context (in this case, ReadOnlyApplicationDbContext and ...
Read more >
Accessing multiple databases from the same DbContext in EF
In order to be able to do your joins on tables or views in different databases you need to do it in the...
Read more >
Using Multiple EF Core DbContexts In a Single Application
It's not possible to do a join between different DbContext instances, because EF Core doesn't know if they are using the same database ......
Read more >
DbContext Lifetime, Configuration, and Initialization
This article shows basic patterns for initialization and configuration of a DbContext instance. The DbContext lifetime. The lifetime of a ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found