Saturday, February 22, 2014

set entity framework connection string programmatically


set entity framework connection string programmatically Error: Code generated using the T4 templates for Database First and Model First development may not work correctly if used in Code First mode. To continue using Database First or Model First ensure that the Entity Framework connection string is specified in the config file of executing application. To use these classes, that were generated from Database First or Model First, with Code First add any additional configuration using attributes or the DbModelBuilder API and then remove the code that throws this exception Solution:
   public static string GetConnectionString(ProfileMaster profile)
        {
            //return string.Format("data source={0};initial catalog={1};user id={2};password={3} multipleactiveresultsets=True;App=EntityFramework", profile.DatabaseIP, profile.DatabaseName, profile.UserName, profile.Password);
            string providerName = "System.Data.SqlClient";
            string serverName = profile.DatabaseIP;
            string databaseName = profile.DatabaseName;

            // 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.IntegratedSecurity = true;

            // 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://*/Models.MoviesDB.csdl|
                        res://*/Models.MoviesDB.ssdl|
                        res://*/Models.MoviesDB.msl";
            return entityBuilder.ToString();
        }

Compiled By: Rajesh Rolen

Read More
Powered By Blogger · Designed By Seo Blogger Templates