20

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

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

4 回答 4

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""";
于 2013-02-03T14:36:05.143 回答
7

我知道这是 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 );

无需担心报价。更清洁。

于 2013-11-19T05:59:40.263 回答
6

使用EntityConnectionStringBuilderSqlConnectionStringBuilder更容易根据需要更改参数。

于 2014-02-04T14:45:12.143 回答
3

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

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

然后在要创建实体实例的任何地方,在参数中传递连接字符串名称:

MyDatabaseEntities entities = new MyDatabaseEntities("CONNECTION_STRING_NAME");

我希望这将有所帮助。

谢谢

于 2015-09-24T18:27:02.797 回答