Dynamically Build Entity Framework Connection At Runtime

sometimes you may need to build your entity framework based connection dynamically during the run time instead of using app.config file.

note that you need to add following using statements

using System.Data.SqlClient;
using System.Data.EntityClient;
using System.Data.Metadata.Edm;

using System.Data.SqlClient;
using System.Data.EntityClient;
using System.Data.Metadata.Edm;

 internal static EntityConnection GetConnection()
        {
            // Specify the provider name, server and database.
            string providerName = "System.Data.SqlClient";
            string serverName = GetServerName() ;
            string databaseName = GetDatabaseName();

            // Initialize the connection string builder for the
            // underlying provider.
            SqlConnectionStringBuilder sqlBuilder =
            new SqlConnectionStringBuilder();

            // Set the properties for the data source.
            sqlBuilder.DataSource = serverName;
            sqlBuilder.InitialCatalog = databaseName;
            sqlBuilder.UserID = userID;
            sqlBuilder.Password = password;

            // Build the SqlConnection connection string.
            string providerString = sqlBuilder.ToString();

            // Initialize the EntityConnectionStringBuilder.
            EntityConnectionStringBuilder entityBuilder =
            new EntityConnectionStringBuilder();

            //Set the provider name.
            entityBuilder.Provider = providerName;

            // Set the provider-specific connection string.
            entityBuilder.ProviderConnectionString = providerString;

            // Set the Metadata location.
            entityBuilder.Metadata = @"res://*/MetaModel.csdl|
            res://*/MetaModel.ssdl|
            res://*/MetaModel.msl";
           

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

            return conn;


        }

Usage Of this Method


       using (var contxt = new YourDatabaseEntities(GetConnection()))
       {
         // your code go here.       
       }

Happy Coding.. !!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s