3

My current connection string that resides in Web.config is this :

  <add name="PersonDBContext" 
       connectionString="Server=111.111.1.11;
       Database=MyProgram;
       User Id=admin;
       Password=12345;
       Integrated Security=False" 
       providerName="System.Data.SqlClient" />

I want to give the same connection string to the program in a dynamic way, this is my attempt :

    EntityConnectionStringBuilder csb = new EntityConnectionStringBuilder();

    csb.ProviderConnectionString = "Data Source=111.111.1.11;Initial Catalog=MyProgram;User Id=admin;Password=12345;Integrated Security=False";
    csb.Provider = "System.Data.SqlClient";

    String entityConnStr = csb.ToString();
    return entityConnStr;

And this is what I get :

Keyword not supported: 'provider'.

Can you tell me what I am doing wrong? And do I need metadata for Code First connection string? Thanks.

EDIT : I figured that I either shouldn't use EntityConnectionStringBuilder or I should give a Metadata for the EntityConnectionStringBuilder class. Can you tell me one of the ways to how to do this?

jason
  • 6,962
  • 36
  • 117
  • 198

4 Answers4

3

Why not pass it as a plain string in the DbContext-derived class' constructor? Like

var ctx = new MyContext("Data Source=111.111.1.11;Initial Catalog=MyProgram;User Id=admin;Password=12345;Integrated Security=False");
Ricardo Peres
  • 13,724
  • 5
  • 57
  • 74
2

What I had to do to have a dynamic connection string, so that users were able to key in or select the server they wanted to connect to, was the following:

In the Model.Context.cs file that EF creates I changed the constructor to:

public partial class Entities : DbContext
{
    public Entities()
        : base(BuildConnectionString)
    {
    }
    ...
}

And then I wrote an extension class EntitiesEx.cs

partial class Entities : DbContext
{
    private static string BuildConnectionString 
    {
        get
        {
            // Specify the provider name, server and database.
            string providerName = "System.Data.SqlClient";
            string serverName = DatabaseController.Server;
            string databaseName = <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.UserID = <user>;
            sqlBuilder.Password = <password>;

            sqlBuilder.IntegratedSecurity = false;

            sqlBuilder.PersistSecurityInfo = true;

            sqlBuilder.MultipleActiveResultSets = 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;

            //assembly full name
            Type t = typeof(Entities);
            string assemblyFullName = t.Assembly.FullName.ToString();

            // Set the Metadata location.
            entityBuilder.Metadata = string.Format("res://{0}/", //Models.Model.csdl|Models.Model.ssdl|Models.Model.msl", 
                assemblyFullName);

            try
            {
                //Test de conexion
                using (EntityConnection conn = new EntityConnection(entityBuilder.ToString()))
                {
                    conn.Open();

                    conn.Close();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Connection error" + ex.Message);
            }

            return entityBuilder.ToString();
        }
    }

As a con, every time you generate your model from the database, you'll have to change your constructor in the Entities class (Model.Context.cs)

fabricio
  • 1,385
  • 17
  • 22
  • As Model.Context.cs gets overwritten, you could instead create a new file, say Entities.cs. Within `public partial class Entities`, as the parameterless constructor is already defined, add a constructor which takes 1 parameter. If you're going to ignore this parameter, you could call the constructor from a parameterless static method. – Zantier Dec 08 '14 at 11:34
1

Dynamic connection string for Code First use simple sql connection string or not EntityConnectionStringBuilder. So you can achieve it as following way.

public static string  DynamicConnectionString(SqlConnectionStringBuilder builder)
{
    SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
    builder.DataSource = "ServerName";
    builder.InitialCatalog = "DatabaseName";
    builder.UserID = "UserId";
    builder.Password = "Password";
    builder.MultipleActiveResultSets = true;
    builder.PersistSecurityInfo = true;    
    return builder.ConnectionString.ToString();
}
MBH
  • 16,271
  • 19
  • 99
  • 149
Dilip Langhanoja
  • 4,455
  • 4
  • 28
  • 37
0

It was simply as this :

string entityConnStr = "Data Source=111.111.1.11;Initial Catalog=MyProgram;User Id=admin;Password=12345;Integrated Security=False";
jason
  • 6,962
  • 36
  • 117
  • 198
  • how will this help to connect other database providers MySql, MSQL etc. Where Is provider ? @jason – Narendra Singh Rathore May 12 '17 at 11:17
  • 1
    @NarendraSinghRathore Agreed... every example I can find does this. If it's code first, they ignore the provider, if they include the provider, it's being treated as though it's modeled. It would be nice to see how the provider is included in a code first example. – bjhuffine Feb 09 '18 at 15:44