0

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

LittleOne
  • 131
  • 1
  • 3
  • 16

2 Answers2

2

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.

Ladislav Mrnka
  • 349,807
  • 56
  • 643
  • 654
  • Yep i tried that one too. I got following error. "Keyword not supported: 'user id'." It means connection string is not supported for entityconnection.I tried above links in question too for that. – LittleOne Jul 16 '12 at 08:38
  • If you are using EDMX you must use valid [entity connection string](http://msdn.microsoft.com/en-us/library/cc716756.aspx) format. What you are passing is not entity connection string format. – Ladislav Mrnka Jul 16 '12 at 08:47
0

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;
    }
LittleOne
  • 131
  • 1
  • 3
  • 16