Click here to Skip to main content
14,429,899 members
Rate this:
Please Sign up or sign in to vote.
See more:
How can I switch between multiple databases using Entity Framework.
The name of the databases will be coming in a drop down list and on selecting the dropdown list item I need to connect to that particular database using Entity Framework.
What is the best solution? Do EF provide any configuration for achieving this? How should the application be configured?
Posted

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

When you use entity framework an "data context" class, derived from ObjectContext is automatically created in the DataModel.Desiner.cs file. This "data context" class has 3 constructors and you should use the 2nd one, that has as parameter the connection string.

So when the user change the database, you should build dynamically the connection string based on the user selection (in the most simple situation if all databases are on the same server only the name of the database should change, so you could use a static text based on the default one and replace only the param for database name by using string.Format) then cache this connection string (for the entire user session context) and use it into your data access code like in the next example:
using (MyDataContextClasss dataContext= new MyDataContextClasss (connectionString))
{
      //You code for accessing the data by using EF!
}
   
Comments
Akhil Mittal 30-Jul-14 23:42pm
   
I tried to do that before posting the question.But when i configure this, it gives an exception and tries to follow a code first approach for another database, whose designer is not inherited in project.
Raul Iloc 31-Jul-14 2:32am
   
1.All databases must have the same structure in order to can be used like I suggested.
2.You should give me the exceptions details in order to can help you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100