问题
Hi I am working on ASP.NET MVC project. Currently I am using Model first approach, where i used to add database manually by using ADO.NET model. Currently I have 4 database and I have 4 connection strings in web.config file.
It was fine till now, since I was working on development environment. But now I need to move my code to live and problem is, in live we have like 40 to 50 databases.
So what I should do is, generate connection string dynamically when user wants to connect to particular database.
I have stored procedure for this which returns connection string and database name.
For example if I have 4 database name like db1, db2, db3 and db4, I need to compare this database name with my stored procedure results database name and if both are equal, then generate connection string equal to that database name.
And also I need to put this in session once i generate connection string, so no need to generate connection string again for particular session.
Can someone help me in this??
回答1:
EF DbContext
as a constructor parameter takes a name of a connection string or connection string itself. So there is no problem in generating any kind of connection string and supply this when creating DdContext.
In our application we have many tenants and have a database per tenant. For every request we lookup what tenant it is and from Settings DB provide a connection string to tenant's own database.
I've not worked with Ado.Net, but from what I see in Google, this is very similar (or based on) to Entity Framework. So down to your particular implementation, there must be a way to provide connection string to database context outwith web.config
.
来源:https://stackoverflow.com/questions/21858082/generate-connection-string-dynamically-in-asp-net-mvc