C#: Class to get the connection string for Entity Framework

 
using System;
using System.Data.SqlClient;
using System.Data.EntityClient;

using System.Globalization;
using System.Configuration;

namespace ProjectFrameworkLayer
{
    public class ProjectFrameworkLayerBase
    {
        internal string GetEntityConnectionString()
        {
            // Initialize the connection string builder for the underlying provider.
            SqlConnectionStringBuilder sqlBuilder =
                new SqlConnectionStringBuilder();

            string dataSource = ConfigurationManager.AppSettings["Entity_DataSource"].ToString(CultureInfo.InvariantCulture);
            string initialCatalog = ConfigurationManager.AppSettings["Entity_InitialCatalogue"].ToString(CultureInfo.InvariantCulture);
            bool integratedSecurity = Convert.ToBoolean(ConfigurationManager.AppSettings["Entity_IntegratedSecurity"]);

            // Set the properties for the data source.
            sqlBuilder.DataSource = dataSource;
            sqlBuilder.InitialCatalog = initialCatalog;
            sqlBuilder.IntegratedSecurity = integratedSecurity;

            if (!sqlBuilder.IntegratedSecurity)
            {
                sqlBuilder.UserID = ConfigurationManager.AppSettings["Entity_UserName"].ToString(CultureInfo.InvariantCulture);
                sqlBuilder.Password = ConfigurationManager.AppSettings["Entity_Password"].ToString(CultureInfo.InvariantCulture);
            }

            sqlBuilder.MultipleActiveResultSets = Convert.ToBoolean(ConfigurationManager.AppSettings["Entity_MultipleActiveResultSets"]);
            sqlBuilder.ApplicationName = ConfigurationManager.AppSettings["Entity_ApplicationName"].ToString(CultureInfo.InvariantCulture);

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

            entityBuilder.Metadata = ConfigurationManager.AppSettings["Entity_MetaData"].ToString(CultureInfo.InvariantCulture);
            entityBuilder.ProviderConnectionString = sqlBuilder.ToString();
            entityBuilder.Provider = ConfigurationManager.AppSettings["Entity_ProviderName"].ToString(CultureInfo.InvariantCulture);

            return entityBuilder.ToString();
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.