Error while Changing the connection string dynamic

2019-09-16 14:15发布

问题:

Im having this problem when changing my entities connection string.

here is the code:

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();

when it tries to change the connection string its giving me an InvalidOperationEsception.

error details: No modifications to connection are permitted after the metadata has been registered either by opening a connection or constructing the connection with a MetadataWorkspace.

Any help its leaving me speachless....

回答1:

I'm assuming that in your example, this.Entities is an instance of an Entity Framework Object Context.

The error message means that you cannot simply assign the new connection string to the Connection property of the Entities object.

Instead, try passing it as a constructor parameter:

  • locate the line where you instantiate Entities:
    this.Entities = new ...();
  • change it to something like this:
    this.Entities = new ...(entityBuilder.ConnectionString.ToString());