Be Careful Subclassing DbContext
i.e. Why doesn’t Entity Framework find my connection string?
Remember that if you subclass from a DbContext
, the default constructor
takes the name of the class as the connection string name.
Your normal WidgetContext
is working just fine: it finds a connection string
called WidgetContext
in the web.config
and loads it right on up.
But then you start adding some instrumentation, and you decide to create a
customized TracingWidgetContext
that inherits from WidgetContext
. Suddenly
it starts trying to create a new database on your local SQLServer instance.
What just happened, I don’t even…
The default, parameter-less DbContext
constructor takes the class name as the
expected connection string name. In this case, the subclass looked for a
TracingWidgetContext
connection string, and not finding one, it just connects
to your local SQLServer. This fall back behavior is probably not expected, and
personally I’d prefer it to just throw.
Anyway, the solution is to pass the name of the desired connection string in the constructor:
class TracingWidgetContext : WidgetContext
{
public TracingWidgetContext()
: base("WidgetContext")
{
}
}
If you can’t do that, because you’re WidgetContext
doesn’t expose that
overloaded constructor, well you should fix it.
But if you can’t you can hack at it and manually set the connection string:
class TracingWidgetContext : WidgetContext
{
public TracingWidgetContext()
{
// Here be dragons
this.Database.Connection.ConnectionString =
ConfigurationManager.ConnectionStrings["WidgetContext"].ConnectionString;
}
}