Rockstart
Rockstart

Reputation: 2377

Selecting database dynamically in Entity Framework

I have multiple SQL databases with the same schema .Say(Database1,Database2....)

How do i dynamically select a database in Entity framework model in runtime?.Since they have the same schema, it does not make sense to import all the data models before hand.

Upvotes: 2

Views: 1106

Answers (1)

Mojtaba
Mojtaba

Reputation: 1620

You can change database connection string like this:

DataModelContainer context = new DataModelContainer(
                    ConnectionOperation.CreateEntityConnection());

And this is CreateEntityConnection Method:

internal static EntityConnection CreateEntityConnection()
            {
                // Start out by creating the SQL Server connection string
                SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();

                // Set the properties for the data source. The IP address network address
                sqlBuilder.DataSource = System.Configuration.ConfigurationManager.AppSettings["Connection"];
                // The name of the database on the server
                sqlBuilder.UserID = "sa";
                sqlBuilder.Password = "12345";
                sqlBuilder.InitialCatalog = "DatabaseName";
                sqlBuilder.IntegratedSecurity = true;
                sqlBuilder.MultipleActiveResultSets = true;
                // Now create the Entity Framework connection string
                EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
                //Set the provider name.
                entityBuilder.Provider = "System.Data.SqlClient";
                // Set the provider-specific connection string.
                entityBuilder.ProviderConnectionString = sqlBuilder.ToString();

                // Set the Metadata location. 
                entityBuilder.Metadata = @"res://*/DataModel.csdl|res://*/DataModel.ssdl|res://*/DataModel.msl";

                // Create and entity connection
                EntityConnection conn = new EntityConnection(entityBuilder.ToString());
                return conn;
            }

Upvotes: 3

Related Questions