Getting 'Context is not constructible. Add a default constructor or provide an implementation of IDbContextFactory."

Solution 1:

Essentially you need a default ctor (that's the error) - but just implementing it would lead to problems.

You'd have to implement the IDbContextFactory for the results to be consistent (or your migration from code won't work etc.).

Migrations actually call your default constructor to make a connection. So you're other ctor won't matter much.

Here is the basic factory...

public class MyContextFactory : IDbContextFactory<MyContext>
{
    public MyContext Create()
    {
        return new MyDBContext("YourConnectionName");
    }
}

You should combine that with injection, to inject and construct your DbContext as you wish.

Solution 2:

If you don't want to spend time looking into the IDbContextFactory option, and to get things working create a default constructor and hard-code the name of the connection string when calling the base DbContext:

public class CustomContext : DbContext
{
    public CustomContext() :base("name=Entities") {} 
}

SRC: http://www.appetere.com/Blogs/SteveM/April-2012/Entity-Framework-Code-First-Migrations

Solution 3:

To complement @nccsbim071 answer, I have to add one more thing... this option doesn't like constructor with default parameters... for instance:

public MyContext(bool paramABC = false) : base("name=Entities") {...}

instead you have to create a non-parameter (default) constructor and the parameter-constructor like old fashion way.

public MyContext() :base("name=Entities") {...} 
public MyContext(bool paramABC) : this() {...}

NOTE:

  • Entities in this case means the connection string name... By convention, the name of the context is the same as the connection string name and since MyContext is not the same as Entities, it's necessary specify it manually.