Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
3.89/5 (2 votes)
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

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:
C#
using (MyDataContextClasss dataContext= new MyDataContextClasss (connectionString))
{
      //You code for accessing the data by using EF!
}
 
Share this answer
 
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.
Member 14774140 30-May-20 3:19am    
can i have an example of it??

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900