How to utilize the ADO.NET Entity Data Model with a SQL connection string

c# entity-framework


I'm attempting to utilize the ADO.NET Entity Data Model so that I can quickly switch the database I'm pointing to. Creating a brand-new connection string may be necessary if databases are changed. Various databases are located on various servers. I thus need the capability of passing my ADO.NET Entity Data Model a customized connection string formatted as follows: "server=severaddress;database=database1;User ID=test;Password=test1234;"

Edited: ObjectContext is implemented by my entity class. The default constructor, a connectionString, and an EntityConnection are the three constructors I may employ. I often see issues stating that the overload constructors cannot detect the word "server" in the connectionstring.

I must either be able to set the connection string before usage or instantiate my repository with a unique connection string.

3/3/2011 7:27:15 PM

Accepted Answer

Entity connection strings are accepted by ObjectContext's constructor. Entity connection strings have three components:

  • Where to find metadata (location of mapping XMLs produced by EDMX file)
  • Data archiving service
  • String of data storage connections (that is what you want to provide)

You may accomplish your goals in a number of ways. In most cases, you need to combine two connection string components:

string format = "metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string=\"{0}\"";
string connectionString = "server=severaddress;database=database1;UserID=test;Password=test1234;"

var context = ModelContext(String.Format(format, connectionString));

The format specifies where the Model.edmx metadata that is used in the assembly and SQL provider as resources may be found. Your connection string is the second component.

Keep in mind that this will only function if all of your databases use the same provider and have the same schema.

3/3/2011 8:10:23 PM

Popular Answer

Simply send the connection string into one of the overloaded constructors of the automatically formed DbContext derived class—I've done this previously.

Related Questions


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