Thursday, February 24, 2011

Create Linq To Entities Connection in Code

If you're like most people, you have several different database servers that you need to connect to and you want to be able to deploy an application to different environments while only changing configuration entries. Linq To Entities has a different connection string and offers a slightly different approach to configuring the connection.

First, the code...


private static EntityConnection connection()
{
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
sqlBuilder.DataSource = System.Configuration.ConfigurationManager.AppSettings["DataSource"].ToString();
sqlBuilder.InitialCatalog = System.Configuration.ConfigurationManager.AppSettings["InitialCatalog"].ToString();
sqlBuilder.IntegratedSecurity = false;
sqlBuilder.UserID = System.Configuration.ConfigurationManager.AppSettings["UserID"].ToString();
sqlBuilder.Password = System.Configuration.ConfigurationManager.AppSettings["Password"].ToString();

EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.Provider = System.Configuration.ConfigurationManager.AppSettings["Provider"].ToString();
entityBuilder.ProviderConnectionString = sqlBuilder.ToString();
entityBuilder.Metadata = System.Configuration.ConfigurationManager.AppSettings["MetaData"].ToString();

EntityConnection entityConnection = new EntityConnection(entityBuilder.ToString());

return entityConnection;
}

The explanation...
First, create a SqlConnectionStringBuilder object. Next, assign the DataSource, InitialCatalog, User and Pass from values stored in the app.config. If you choose not to use Integrated Security set that property to false.

Now, create an EntityConnectionStringBuilder object. Assign the provider and metadata values. Assign the ProviderConnectionString property to the SqlConnectionStringBuilder.ToString() value.

Finally, create a new EntityConnection object and pass it the EntityConnectionStringBuilder.ToString() and you have yourself a new EntityConnection.

No comments:

Post a Comment