Dynamic Database Switching in Entity Framework
Managing multiple databases within a web API requires efficient runtime connection switching. This solution details how to achieve this:
SqlConnectionStringBuilder
and EntityConnectionStringBuilder
to construct the appropriate connection string.ChangeDatabase
extension method (from the ConnectionTools
class) allows for dynamic alteration of the data context's connection:<code class="language-csharp">// Dynamically switch the database connection var selectedDb = new MyDbEntities(); selectedDb.ChangeDatabase(initialCatalog: "new_catalog", userId: "new_user");</code>
The above is the detailed content of How to Dynamically Switch Databases in Entity Framework at Runtime?. For more information, please follow other related articles on the PHP Chinese website!