3355307
3355307

Reputation: 1678

Entity Framework database first and dynamic connection string for 100+ SQL Server databases

I am new to Entity Framework and want to know how to modify the connection string in code.

Here is my code

using (var context = new PushjobModel.PushjobEntities())
{
    var list = context.GetAllActivePushjobs();

    foreach (PushjobModel.Pushjob item in list)
    {
        item.IsActive = false;
        item.IsSent = true;
    }

    context.SaveChanges();
}

I have a configuration file in my ASP.NET webforms application which contains a list of connection strings for 100+ databases. Before I call context.GetAllActivePushjobs(); I want to change the connection string.

With old ADO.NET I have been using following approach for long time and it works perfectly

spPremisesReadTableAdapter taPremises = new spPremisesReadTableAdapter();

taPremises.Connection.ConnectionString = GetConnectionString(CompanyName);

taPremises.GetData();
...

public static void GetConnectionString(string CompanyName)
{
    string connectionstring = System.Web.Configuration.WebConfigurationManager.ConnectionStrings[CompanyName].ConnectionString;
}

Can anyone help?

Upvotes: 0

Views: 1370

Answers (3)

beastieboy
beastieboy

Reputation: 883

May be you could try this:

using (var context = new PushjobModel.PushjobEntities(GetConnectionString(CompanyName)))
{
    var list = context.GetAllActivePushjobs();

    foreach (PushjobModel.Pushjob item in list)
    {
        item.IsActive = false;
        item.IsSent = true;
    }

    context.SaveChanges();
}

public static void GetConnectionString(string CompanyName)
{
    string connectionstring = System.Web.Configuration.WebConfigurationManager.ConnectionStrings[CompanyName].ConnectionString;
}

Upvotes: 0

Maziar Taheri
Maziar Taheri

Reputation: 2338

I think what you are looking for is the class EntityFrameworkConnectionStringBuilder

Take a look at MSDN page

Upvotes: 1

marc_s
marc_s

Reputation: 754478

You just need to provide the name of the connection string entry to your constructor of your DbContext:

using (var context = new PushjobModel.PushjobEntities(name-of-connection-string-here))
{
   .....
}

Upvotes: 0

Related Questions