1

Migrating from ObjectContext to DbContext code-generation, I realized that context class generated (which inherits from DbContext) has no constructor that receives connectionString neither EntityConnection (like ObjectContext child class had).

This is a problem in my application since I need to instantiate my context dynamically from the concrete Type, using a runtime generated connection string.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Tuk
  • 143
  • 2
  • 10

2 Answers2

1

On your class that inherits the DbContext, you should be able to specify the base constructor that takes the connection sting:

public class MyDbContext : DbContext
{
    public MyDbContext(string connString)
        : base(connString)
    {
    }
}

You will have to use the SQLConnection builder though:

SqlConnectionStringBuilder connBuilder= new SqlConnectionStringBuilder(dbConnString);

And use it in your constructor:

MyDbContext dbContext = new MyDbContext(connBuilder.ToString());
ZanderAdam
  • 434
  • 2
  • 13
  • Hi Ezakiel! That's the more logical way to do it. But I can't modify my class MyDbContext adding that constructor. ObjectContext suited my needs in this providing out of the box constructor with connection string, can't believe this was no considered in DbContext – Tuk May 02 '13 at 15:19
  • Edited response and added "partial" to the class definiton resolve your issue; now you haven't to edit the generated code – jlsfernandez Jun 26 '13 at 11:12
  • Isn't it supposed to be generated right out of the box? – Johnny_D Feb 14 '14 at 11:50
0

This helped me:

 public MyDatabaseContext():base("name=MyConnectionString")
  {
  }
Maxim Eliseev
  • 3,248
  • 4
  • 29
  • 35