Tuk
Tuk

Reputation: 153

Entity Framework DbContext dynamic instantiation with custom Connection String

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.

Upvotes: 1

Views: 3069

Answers (2)

Maxim Eliseev
Maxim Eliseev

Reputation: 3504

This helped me:

 public MyDatabaseContext():base("name=MyConnectionString")
  {
  }

Upvotes: 0

ZanderAdam
ZanderAdam

Reputation: 434

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());

Upvotes: 1

Related Questions