0

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?

2

3 Answers 3

1

I think what you are looking for is the class EntityFrameworkConnectionStringBuilder

Take a look at MSDN page

Sign up to request clarification or add additional context in comments.

Comments

0

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))
{
   .....
}

2 Comments

Thanks. I created another connection string on the pattern of entity framework and it worked
existing connection strings in config file in the format <add name="test100" connectionString="data source=(local);initial catalog=TestXYZ100;Integrated Security=True""></add> is there any way so that I can pass this connection string and its converted into entity framework style connection string because I have to create duplicate connection string now one for old ado.net connectivity and otherone for entity framework connectivity
0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.