问题
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.
回答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());
回答2:
This helped me:
public MyDatabaseContext():base("name=MyConnectionString")
{
}
来源:https://stackoverflow.com/questions/16341163/entity-framework-dbcontext-dynamic-instantiation-with-custom-connection-string