LittleOne
LittleOne

Reputation: 131

Set dynamic ConnectionString Entity Framework

I developed Asp.net application with Entity Framework and now i need to change entity connection string at run time.I tried following way.

public class DataLayer(){

static DataLayer()
{
((EntityConnection)_dbEntity.Connection).StoreConnection.ConnectionString =    GetConnectionString();

//GetConnectonString() returns "user id=xxxx;password=xxxx;database=xxxx;server=xxx.xxx.xx.xx"
}

static DBContext _dbEntity = new DBContext();
//other codes
}

And I checked following links too.Still I couldn't change it.

http://msdn.microsoft.com/en-us/library/bb738533(v=vs.90).aspx

http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/8a89a728-6c8d-4734-98cb-11b196ba11fd

Upvotes: 0

Views: 3118

Answers (2)

LittleOne
LittleOne

Reputation: 131

Finally I got answer.I apply this dbcontext to a Entity datasource of a grid.So it create context at runtime it was fixed.So I changed that one.

 protected void EntityDataSource1_ContextCreating(object sender, EntityDataSourceContextCreatingEventArgs e)
    {
        var dp=new DBContext();
        e.Context = dp;
    }

Upvotes: 0

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364349

You cannot change connection string of existing context. If you want to control connection string at runtime you must pass connection string to DbContext or ObjectContext constructor.

Btw. as I already mentioned in comment - you must not use static context in ASP.NET. You should never use static context at all. Your application will not work correctly if you will continue with static context.

Upvotes: 2

Related Questions