brudert
brudert

Reputation: 537

DbContext constructor with connString causes problems with EF Migrations and EF Powertools

I would like to pass a connection string to the constructor of DbContext. The way to do this has been answered here: Pass connection string to code-first DbContext

(code if you don't like to click)

public MyContext(string connString)
    : base(connString)
{

}

However, when I attempt to enable migrations I receive the error: "The target context '...' is not constructible. Add a default constructor or provide an implementation of IDbContextFactory."

Also, when I attempt to use EF PowerTools to generate an Entity Data Model is receive the error: "A constructible type deriving from DbContext could not be found in the selected file."

Is this a common problem? I have a fix, but it feels like a hack. Any one else have to deal with this before?

Upvotes: 0

Views: 4303

Answers (1)

NSGaga
NSGaga

Reputation: 14302

Add also an empty constructor, e.g...

public MyContext()
{
}

Thing is once you define a parametrized ctor your default one gets hidden

e.g. see Why does the default parameterless constructor go away when you create one with parameters

That's also one way of 'hiding' default construction from the outside users.


Usually you don't even expose that 'other' ctor to the outside - as its 'yours', you just hardcode inside what you need. Or alternatively and better - you use the 'app.config' to specify the connection string. For details (and problems with it) see...

Migration does not alter my table
Migration not working as I wish... Asp.net EntityFramework

Upvotes: 4

Related Questions