Changing the connection string dynamically (for each request) to Entity Framework 7 / MVC 6

I have an MVC 6 application on which I need to connect to another database (i.e. a physical file, but the same schema) depending on who is accessing it. That is: each client of the web application will have data allocated in the SQL database (on Azure with different characteristics, price levels, etc.), but all these databases will use the same relational scheme and, of course, Entity Framework context class.

var cadConexion = @"Server=(localdb)\mssqllocaldb;Database=DBforCustomer1;Trusted_Connection=True;";
services.AddEntityFramework().AddSqlServer().AddDbContext<DAL.ContextoBD>(options => options.UseSqlServer(cadConexion));

The problem is that if I register the service this way, I linked it to a specific database for a particular client, and I don’t know if I can change it when starting the middleware (this would be good because I know who is calling in the door).

I know that I can construct a database context by passing a connection string as a parameter, but that would mean that I have to create a database context at runtime (at the beginning of the pipeline) for each query, and I don't know if it could be potentially ineffective or bad practice. In addition, I think that I can not register the database context as a service for entering it on my controllers ...

What is the right approach for this? Does anyone have a similar configuration working on production?

Thanks in advance

+2
source share
2 answers

First of all, I do not recommend replacing connection strings with a query.

. . DbContext .

.AddDbContext , DI, . DbContext .

+2

, , , , , , ...

- ( ) API- Azure, "Elastic Database Tools", , Microsoft, , SaaS ( ) ( ).

:

https://azure.microsoft.com/en-us/documentation/articles/sql-database-elastic-scale-get-started/

!

+3

Source: https://habr.com/ru/post/1662096/


All Articles