Set Entity Framework Connection String at Runtime in C#

c# entity-framework

Question

I need to set my Entity Framework connection string at runtime. Right now, I have the following:

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

When I execute the code above (with the {parameter} values replaced), I get the following error:

Keyword not supported: 'data source'.

What am I doing wrong?

1
20
2/3/2013 4:33:51 PM

Accepted Answer

Change this.

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"";

To this (note how i escaped the " character as "" )

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""";
21
2/3/2013 2:36:05 PM

Popular Answer

I know this was asked 10 months ago, but I found an easier way to specify the connectionString:

If your config file has it as:

<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" />

You can specify it as -

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

No need to worry about quotes. Lot cleaner.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow