I have a web API project which references my model and DAL assemblies. The user is presented with a login screen, where he can select different databases.
I build the connection string as follows:
public void Connect(Database database)
{
//Build an SQL connection string
SqlConnectionStringBuilder sqlString = new SqlConnectionStringBuilder()
{
DataSource = database.Server,
InitialCatalog = database.Catalog,
UserID = database.Username,
Password = database.Password,
};
//Build an entity framework connection string
EntityConnectionStringBuilder entityString = new EntityConnectionStringBuilder()
{
Provider = database.Provider,
Metadata = Settings.Default.Metadata,
ProviderConnectionString = sqlString.ToString()
};
}
First of all, how do I actually change the connection of the data context?
And secondly, as this is a web API project, is the connection string (set at login per above) persistent throughout the user's interaction or should it be passed every time to my data context?
You can get the connection string from the web.config, and just set that in the EntityConnectionStringBuilder constructor, and use the EntityConnectionStringBuilder as an argument in the constructor for the context.
Cache the connection string by username. Simple example using a couple of generic methods to handle adding/retrieving from cache.
DbContext
has a constructor overload that accepts the name of a connection string or a connection string itself. Implement your own version and pass it to the base constructor:Then simply pass the name of a configured connection string or a connection string itself when you instantiate your
DbContext
The created class is 'partial'!
... and you call it like this:
so, you need only create a partial own class file for original auto-generated class (with same class name!) and add a new constructor with connection string parameter, like Moho's answer before.
After it you able to use parametrized constructor against original. :-)
example:
Add multiple connection strings in your web.config or app.config.
Then you can get them as a string like :
Then use the string to set :
It is better explained here :
Read connection string from web.config
I wanted to have multiple datasources in the app config. So after setting up a section in the app.config i swaped out the datasource and then pass it into the dbcontext as the connection string.
This took me a bit to figure out. I hope it helps someone out. I was making it way too complicated. before this.
In my case I'm using the ObjectContext as opposed to the DbContext so I tweaked the code in the accepted answer for that purpose.