动态更改连接字符串时出错

时间:2012-01-05 22:08:05

标签: asp.net linq linq-to-entities connection-string entity-model

我在更改实体连接字符串时遇到此问题。

这是代码:

SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
                        sqlBuilder.DataSource = @"KURT-PC\SQLEXPRESS";
                        sqlBuilder.InitialCatalog = "KurtDB";
                        sqlBuilder.UserID = "Admin";
                        sqlBuilder.Password = "123456";
                        sqlBuilder.IntegratedSecurity = false;
                        sqlBuilder.MultipleActiveResultSets = true;

                        EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
                        entityBuilder.Provider = "System.Data.SqlClient";
                        entityBuilder.ProviderConnectionString = sqlBuilder.ToString();
                        entityBuilder.Metadata = @"res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl";

                        this.Entities.Connection.ConnectionString = conn.Connection.ConnectionString = entityBuilder.ConnectionString.ToString();

当它尝试更改连接字符串时,它会给我一个InvalidOperationEsception。

错误详情: 通过打开连接或使用MetadataWorkspace构建连接来注册元数据后,不允许修改连接。

任何帮助它让我无言以对......

1 个答案:

答案 0 :(得分:4)

我假设在您的示例中,this.Entities是实体框架对象上下文的实例。

错误消息表示您不能简单地将新连接字符串分配给Connection对象的Entities属性。

相反,尝试将其作为构造函数参数传递:

  • 找到实例化实体的行:
    this.Entities = new ...();
  • 将其更改为以下内容:
    this.Entities = new ...(entityBuilder.ConnectionString.ToString());