0

In a Net Core 5 Web API application, I need to change the connection string of a secondary dbcontext with information obtained from the main dbcontext

There are two dbcontext:

DbContextMaster - static connection string

DbContextChild - dynamic connection string. Use the template in appsettings like this:

"DbContextChild": "Data Source=server;Initial Catalog={dbName};Integrated Security=False;User Id=username;Password="

When starting the application:

  1. I get a header parameter to identify the tenant (so far ok)

  2. I need to perform a query with this parameter using a DbContextMaster to get the database name. If the value of the header parameter identifying the tenant DOES NOT exist in this database, it must return badRequest, if it exists, must change DbContextChild template with database name from tenant, so that only then does the controller getting the data from the DbContext Child respond to the requests.

I have many questions about how to carry out such an implementation. Is there any way to intercept the call from all controllers by doing the above checks? Or would it be necessary to have a base controller and everyone else inherit it?

Marcoscdoni
  • 955
  • 2
  • 11
  • 31
  • Have trouble to realizing updating appsetting.json at runtime? Can [this answer](https://stackoverflow.com/a/58660997) help you? – Tiny Wang Sep 21 '21 at 06:59
  • I don't need to change the content of appsettings. In the configuration file I have a connection string template. Depending on the tenant parameter sent via header the connection string parameter will be replaced with the database name belonging to that specific tenant – Marcoscdoni Sep 21 '21 at 17:47
  • Thanks for your reply and, [this answer](https://stackoverflow.com/questions/20216147/entity-framework-change-connection-at-runtime)? – Tiny Wang Sep 22 '21 at 01:42
  • so let me get this straight. You've got a master database that contains some information about your tenants and the database name each tenant should use. Master db context is static and known the whole time. What you need is when a request comes in from tenant 'Pokemon', you must query some table in the master database to see if a record exists, and if it does grab the name of its database and create a connection string that way. Is this correct? – O.MeeKoh Oct 04 '21 at 19:18

0 Answers0