-1

I've got an application that's an extension for another application. The primary application has a context which provides a connection string. In the past, I've setup entity framework and the first step is to set to connection string.

In this case, I can't set the connection string because I don't have it until runtime. Can I still use Entity Framework? If so, how do I set it up?

P.Brian.Mackey
  • 43,228
  • 68
  • 238
  • 348
  • Looks like a duplicate question here: http://stackoverflow.com/questions/6003085/how-do-i-programmatically-set-the-connection-string-for-entity-framework-code-fi – G_P Feb 02 '12 at 14:50
  • @G_P - At a superficial level that question is a duplicate. There is so much going on in that other guy's question regarding SQL CE/SQL that I don't understand and I don't need. So I disagree. – P.Brian.Mackey Feb 02 '12 at 14:57

6 Answers6

3

Absolutely:

SqlConnection dbConn = new SqlConnection("your_connection_string");
EntityConnection entityConnection = new EntityConnection(dbConn);
var yourEdmx = new DbModel(entityConnection);
ken2k
  • 48,145
  • 10
  • 116
  • 176
2

Use EntityConnectionStringBuilder Class.

EntityConnectionStringBuilder entityBuilder =
    new EntityConnectionStringBuilder();
entityBuilder.Provider = providerName;
entityBuilder.ProviderConnectionString = providerString;
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
1

Yes, you can specify a connection when creating the Context.

H H
  • 263,252
  • 30
  • 330
  • 514
0

Simple method:

var DB = new Your_Entities();
DB.Database.Connection.ConnectionString = "Your_Connection_String";
Graham Laight
  • 4,700
  • 3
  • 29
  • 28
0

I had this problem with a project... everything is fine, all wonders... When you run the application in you computer, how do you adapt the database connection to the different users?

I did everything here and other many post similar to this, and nothing seams to work... Yes, the code works, the data context catch the new info for the connection, but it simply DON'T WORK... :'(

I found a lifesaver example that solve my problems, it's a bunch of code but, DBCon has the information of the new connection:

Encripter enc = new Encripter();
string strconfig = u.readFile(u.ubicacionActual() + "\\conn.config");
DBCon dbcon = JsonConvert.DeserializeObject<DBCon>(enc.decrypt(strconfig));

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
EntityConnectionStringBuilder efb = new EntityConnectionStringBuilder(config.ConnectionStrings.ConnectionStrings["ProyectEntities"].ConnectionString);
SqlConnectionStringBuilder sqb = new SqlConnectionStringBuilder(efb.ProviderConnectionString);

// Now we can set the datasource
sqb.DataSource = dbcon.datasource;
sqb.InitialCatalog = dbcon.catalog;
sqb.UserID = dbcon.user;
sqb.Password = dbcon.password;

efb.ProviderConnectionString = sqb.ConnectionString;

// to rewrite the app.config!
ChangeEFConnectionString("ProyectEntities", efb.ProviderConnectionString);

ProyectEntities db = new ProyectEntities(); // dbcontext

The magic function (Well it's not really magic! Just overwrite the app.config)

private bool ChangeEFConnectionString(string connStringName, string newValue)
{
    try
    {
        //CreateXDocument and load configuration file
        XDocument doc = XDocument.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
        //Find all connection strings
        var query1 = from p in doc.Descendants("connectionStrings").Descendants()
                     select p;
        //Go through each connection string elements find atribute specified by argument and replace its value with newVAlue
        foreach (var child in query1)
        {
            foreach (var atr in child.Attributes())
            {
                if (atr.Name.LocalName == "name" && atr.Value == connStringName)
                {
                    if (atr.NextAttribute != null && atr.NextAttribute.Name == "connectionString")
                    {
                        // Create the EF connection string from existing
                        EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder(atr.NextAttribute.Value);
                        //
                        entityBuilder.ProviderConnectionString = newValue;
                        //back the modified connection string to the configuration file
                        atr.NextAttribute.Value = entityBuilder.ToString();
                    }
                }
            }
        }
        doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
        return true;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
        return false;
    }
}

All credits to a Bahrudin Hrnjica

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
Birkto
  • 71
  • 4
0

You can also set the context database default connection factory after the fact:

dbContext.Database.DefaultConnectionFactory = someConnectionString;
PinnyM
  • 35,165
  • 3
  • 73
  • 81