在C#中运行时设置实体框架连接字符串

时间:2013-02-03 14:31:47

标签: c# entity-framework

我需要在运行时设置我的Entity Framework连接字符串。现在,我有以下内容:

string connectionString = "metadata=res://*/DataModels.CustomerDataModel.csdl|res://*/DataModels.CustomerDataModel.ssdl|res://*/DataModels.CustomerDataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=tcp:{serverName},{portNumber};initial catalog={databaseName};user id={username};multipleactiveresultsets=True;application name=EntityFramework"";
using (CustomerEntities entities = new CustomerEntities(connectionString))
{
  CustomerEntity entity = new CustomerEntity();
  // do more
  entities.CustomerEntities.Add(entity);
  entities.SaveChanges();
}

当我执行上面的代码时(替换了{parameter}值),我收到以下错误:

  

不支持关键字:'数据源'。

我做错了什么?

4 个答案:

答案 0 :(得分:21)

改变这一点。

string connectionString = "metadata=res://*/DataModels.CustomerDataModel.csdl|res://*/DataModels.CustomerDataModel.ssdl|res://*/DataModels.CustomerDataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=tcp:{serverName},{portNumber};initial catalog={databaseName};user id={username};multipleactiveresultsets=True;application name=EntityFramework"";

对此(请注意我是如何将“字符”转义为“)”

string connectionString = @"metadata=res://*/DataModels.CustomerDataModel.csdl|res://*/DataModels.CustomerDataModel.ssdl|res://*/DataModels.CustomerDataModel.msl;provider=System.Data.SqlClient;provider connection string= ""data source=tcp:{serverName},{portNumber};initial catalog={databaseName};user id={username};multipleactiveresultsets=True;application name=EntityFramework""";

答案 1 :(得分:8)

我知道这是在10个月前提出的,但我找到了一种更简单的方法来指定connectionString:

如果您的配置文件包含:

<connectionStrings>
<add name="CustomerDataModel" connectionString="metadata=res://*/EntityFramework.CustomerDataModel.csdl|res://*/EntityFramework.CustomerDataModel.ssdl|res://*/EntityFramework.CustomerDataModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.\CustomerDataModel;initial catalog=CustomerDB;integrated security=True;multipleactiveresultsets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

您可以将其指定为 -

public const string ConnectionString = @"name=CustomerDataModel";
..
CustomerDBContext context = new CustomerDBContext(ConnectionString );

无需担心报价。很多清洁工。

答案 2 :(得分:7)

使用EntityConnectionStringBuilderSqlConnectionStringBuilder可以更轻松地根据需要更改参数。

答案 3 :(得分:2)

在web.config中设置多个连接字符串,然后按照以下步骤操作:

public partial class MyDatabaseEntities
{
    public MyDatabaseEntities(string connection)
        : base(connection)
    {
    }
}

然后在您想要创建实体实例的任何地方,在参数:

中传递连接字符串名称
MyDatabaseEntities entities = new MyDatabaseEntities("CONNECTION_STRING_NAME");

我希望这会有所帮助。

由于