2

我有多个具有相同架构的 SQL 数据库。说(Database1,Database2 ....)

如何在运行时动态选择实体框架模型中的数据库?由于它们具有相同的架构,因此事先导入所有数据模型没有意义。

4

1 回答 1

3

您可以像这样更改数据库连接字符串:

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

这是CreateEntityConnection方法:

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;
            }
于 2013-05-25T18:08:05.737 回答