How do I prevent CodeFirst from trying to run migrations on my database?
I am getting
Invalid object name 'dbo.__MigrationHistory'.
public class MyDbConfiguration : DbConfiguration
As the comments to my question note, what I was doing should work. The problem turned out to be with how my project was using the Unity dependency injection container.
For all types that were being registered, I was also configuring a virtual method interceptor. I was registering and configuring my
DbContext like this:
Container.RegisterType<IInstitutionContext, InstitutionContext>(); Container.Configure<Interception>() .SetInterceptorFor(typeof(InstitutionContext), new VirtualMethodInterceptor());
The problem was the
VirtualMethodInterceptor. The interceptor was causing the
InstitutionContext class to be wrapped.
Entity Framework 6 maintains a registry associating a
DbContext type to its configured
DbInitializer. When it sees a new type of
DbContext for the first time, it looks in its internal registry to see which
DbInitializer should be called. It tries to find the
DbInitializer based on the
DbContext's type. If it doesn't find a registered
DbInitializer, it uses the default initializer, which is
But when the
VirtualMethodInterceptor is configured for a given
DbContext type (in my case,
InstitutionContext), the Unity container won't instantiate the
InstitutionContext directly. Instead it wraps
InstitutionContext in order to be able to intercept the virtual methods. When EF6 tries to locate the type to look up its
DbInitializer, it checks the type of the DbContext, which is a wrapped type, NOT the
InstitutionContext type. So it never finds a matching type, and falls back to using the default database initializer.
Removing the interceptor for the
DbContext types fixed the problem.
tl;dr: Make sure your
DbContext isn't wrapped by another type. For EF6's
DbInitializer configuration to work, it must be checking the right
DbContext type. It won't work if the
DbContext is inherited from a type that has a registered
DbInitializer, and it won't work if the
DbContext is a wrapper type.