c# - 在 Entity Framework 中动态选择数据库

标签 c# sql entity-framework entity-framework-4

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

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

最佳答案

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

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

关于c# - 在 Entity Framework 中动态选择数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16752371/

相关文章:

c# - 如何克隆微软图表控件?

sql - 锁定 SQL Server 存储过程

php - 如何优化php文件中的这段代码

c# - Entity Framework ,包含和条件运算符(使用 charindex 之类的)

entity-framework - DBContext 应该全局定义还是每次都显式创建?

c# - Entity Framework : difference between Detach and AsNoTracking

c# - 查找表达式 C# 中存在的数值

java - C#接口(interface)协方差,指定参数类型

c# - 如何使用 FileInfo 类,避免 PathTooLongException?

sql - 如何查找存储在 SQL Server 2008 表中的最旧记录?