How do I prevent CodeFirst from trying to run migrations on my database?
I am getting SqlException
thrown with the following error message:
Invalid object name 'dbo.__MigrationHistory'.
These exceptions are being caught and logged by my logging framework. I need to prevent the exception from happening so lots of spurious log messages aren't generated by my application.
I understand the __MigrationHistory
table is part of Code First Migrations. I do use Code First, but I do not use its migrations. (The project uses FluentMigrator instead.) According to this blog post and this answer, to disable the error, I need to do the following:
static InstitutionContext()
{
System.Data.Entity.Database.SetInitializer<InstitutionContext>(null);
}
(This, of course, for a DbContext
object named InstitutionContext
.)
I have done this, and verified that the line of code is getting hit. However, I am still getting the error in the logs.
This answer explains what is happening, and I think it is basically correct. In short, EF is probing the __MigrationsHistory
table, throws an exception when it doesn't find it, and then continues without doing anything with migrations. But the answer does not explain how to suppress the exception from happening.
How do I prevent the EF Code First migrations from trying to run and throwing its SqlException
?
UPDATE 1
I tried configuring the setting via the App.config/Web.config file, and that didn't work either. I also tried moving it from a static method on my DbContext
to its own configuration class, like this:
public class MyDbConfiguration : DbConfiguration
{
public MyDbConfiguration()
{
SetDatabaseInitializer<InstitutionContext>(null);
}
}
The class is in the same assembly as the DbContext
like it's supposed to be. This didn't work either.
UPDATE 2
The problem turned out to be related to the Unity container, and how EF and Unity were interacting given how I had both configured. See my answer below.