在实体框架中动态选择数据库

本文关键字:选择 数据库 动态 实体 框架 | 更新日期: 2023-09-27 18:15:25

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

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

在实体框架中动态选择数据库

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

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;
            }