Search code examples
c#.netentity-framework.net-4.5entity-framework-migrations

EF Migration on Test Database breaking all integration tests after merge


I'm working on a .NET 4.5.2 project that creates an In-Memory db from an .mdf file every time we run the Integration tests.

The db works fairly well most of the time, but sometimes, when we make changes on the schema of a table, or add/delete a table altogether, we get problems like the following:

Message: 
    OneTimeSetUp: System.Data.SqlClient.SqlException : There is already an object named 'SomeTable' in the database

We have narrowed it down to the fact that EF migrations get all messed up when we want to update the test db schema after a merge (known issue). It seems like adding an empty migration everytime we have one of these issues fixes the problem, however, that workaround it's very tacky.

My question is: Is there a way to prevent this kind of issues? Maybe a cleaner workaround?

For some extra content, I'll describe how we're doing things (maybe we're messing up somehow):

We have a Db.mdf file that gets loaded by a LocalDbHelper before running any test:

enter image description here

With this code:

public static void PrepareEmptyDb()
    {
        var migrationConfiguration = new Configuration()
        {
            AutomaticMigrationsEnabled = true,
            AutomaticMigrationDataLossAllowed = true
        };

        var migrator = new DbMigrator(migrationConfiguration);
        migrator.Update();
    }

This code is meant to be run in a OneTimeSetup at the IntegrationTestBase class.

And this is the code in the Configuration class (this is at our code first Persistance project, where all migrations reside):

internal sealed class Configuration : DbMigrationsConfiguration<Context.DbContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
    }

    protected override void Seed(Context.DbContext context)
    {
        context.Settings.AddOrUpdate(
            p => p.Name,
            new Setting { Name = SettingNames.RoundingDirection, Value = "Up" },
            new Setting { Name = SettingNames.RoundingValue, Value = "10" },
            new Setting { Name = SettingNames.RateCacheLifetimeMinutes, Value = "30" });
    }
}

Any help would be greatly appreciated, since this issue has really been annoying us for a while now.

EDIT: I've found this link that seem to suggest that, for older versions of .NET, this workaround was the recommended fix suggested by Microsoft themselves, but if anyone has a better way to fix it (or to automatize it) it would be greatly appreciated.


Solution

  • Adding an empty migration seems to be the only way to fix this. No workarounds or fixes other than upgrading to Core, sadly.