在运行时更改实体连接字符串

时间:2014-03-19 00:56:47

标签: entity-framework

我使用实体框架6.02和Vb.net与Sql server数据库。

我在4个不同的服务器上有4个相同的数据库。我通过向导使用其中一个数据库创建实体。现在我想在运行时修改连接字符串,以便与其他数据库连接。

这就是我改变的方式:

这是visual studio中app.config上的连接字符串(我已使用{SERVER}更改了服务器名称,使用{DATABASE}更改了数据库名称

<connectionStrings>
 <add name="MyEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source={SERVER};initial catalog={DATABASE};integrated security=True;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient" />
 </connectionStrings>

这是更改连接字符串的代码:

Public Cnstring as string

Dim connstringtemplate As String = System.Configuration.ConfigurationManager.ConnectionStrings(1).ConnectionString.ToString

Cnstring = connstringtemplate.Replace("{DATABASE}", "MyDB2").Replace("{SERVER}","PC2").Tostring

这是我的实体类,接受连接字符串作为参数:

Partial Public Class MyEntities
 Inherits DbContext   
Public Sub New(connectionString  As String)
     If String.IsNullOrWhiteSpace(connectionString) Then
          Throw New ArgumentNullException("connectionString")
     End If
     Database.Connection.ConnectionString = connectionString
 End  Sub

这是实体声明:

context = New MyEntities(cnstring)

但是现在在运行时我在行上出现错误

Database.Connection.ConnectionString = connectionString
An unhandled exception of type 'System.ArgumentException' occurred in System.Data.dll

Additional information: Keyword not supported: 'metadata'.

此代码有什么问题?

谢谢!

1 个答案:

答案 0 :(得分:1)

DbContext构造函数接受连接字符串作为参数。 你可能最好建立一个连接字符串并将其传递给构造函数。

我使用了类似的东西:

// the model name in the app.config connection string (any model name - Model1?)
private static string GetConnectionString(string model, settings)
{
    // Build the provider connection string with configurable settings
    var providerSB = new SqlConnectionStringBuilder
    {
        InitialCatalog = settings.InitialCatalog,
        DataSource = settings.DataSource,
        UserID = settings.User,
        Password = settings.Password
    };

    var efConnection = new EntityConnectionStringBuilder();
    // or the config file based connection without provider connection string
    // var efConnection = new EntityConnectionStringBuilder(@"metadata=res://*/model1.csdl|res://*/model1.ssdl|res://*/model1.msl;provider=System.Data.SqlClient;");
    efConnection.Provider = "System.Data.SqlClient";
    efConnection.ProviderConnectionString = providerSB.ConnectionString;
    // based on whether you choose to supply the app.config connection string to the constructor
    efConnection.Metadata = string.Format("res://*/Model.{0}.csdl|res://*/Model.{0}.ssdl|res://*/Model.{0}.msl", model); ;
    return efConnection.ToString();

}