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.

2 Answers 2

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());
Sign up to request clarification or add additional context in comments.

3 Comments

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
Edited response and added "partial" to the class definiton resolve your issue; now you haven't to edit the generated code
Isn't it supposed to be generated right out of the box?
0

This helped me:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.