实体框架代码首次自定义迁移事务异常

时间:2017-05-09 11:41:36

标签: c# entity-framework transactions

我已经定义了一个自定义迁移类,如下所示:

public class MyMigrate<TMigrationsConfiguration> : IDatabaseInitializer<MyContext>
    where TMigrationsConfiguration : DbMigrationsConfiguration<MyContext>, new()
{
    private readonly TMigrationsConfiguration _config;

    public MyMigrate(string connectionString, string invariantProvider)
    {
        var typeInitialCreate = typeof(MyConfiguration);

        var migrationsAssembly = Assembly.GetAssembly(typeInitialCreate);
        var migrationsNamespace = typeInitialCreate.Namespace;

        _config = new TMigrationsConfiguration
        {
            TargetDatabase = new DbConnectionInfo(connectionString, invariantProvider),
            MigrationsAssembly = migrationsAssembly,
            MigrationsNamespace = migrationsNamespace,
        };
    }

    public void InitializeDatabase(MyContext context)
    {
        // Update the migrator with the config containing the right connection string
        var dbMigrator = new DbMigrator(_config);

        var dbm = dbMigrator.GetDatabaseMigrations();
        var local = dbMigrator.GetLocalMigrations();
        var pending = dbMigrator.GetPendingMigrations();

        dbMigrator.Update();
    }
}

这是实际的配置类,它会做一些额外的播种。该类位于另一个程序集中。

public sealed class MyMigrationConfiguration : DbMigrationsConfiguration<MyContext>
{
    public MigrationConfiguration()
    {
        AutomaticMigrationsEnabled = false;
        ContextKey = "MyContext";
    }
}

这是启用迁移后生成的配置文件。它用于使用生成的迁移文件识别和加载程序集。

internal sealed class MyConfiguration : DbMigrationsConfiguration<MyContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
        ContextKey = "MyContext";
    }
}

}

我这样执行:

private static void MigrateToLatest()
    {
        var conString = System.Configuration.ConfigurationManager.ConnectionStrings["MyContext"].ConnectionString;

        Database.SetInitializer(new MyMigrate<MigrationConfiguration>(conString, Migrate.SqlInvariantProvider));

        using (var fctx = new MyContext(conString, "SYSTEM"))
        {
            if (!fctx.Database.CompatibleWithModel(false))
            {
                fctx.Database.Initialize(false);
            }
        }
    }

当我调用Initialize(false)时,我收到以下错误消息:

`EntityFramework.dll中发生了'System.InvalidOperationException'类型的未处理异常

附加信息:传入的事务与当前连接无关。只能使用与当前连接相关的交易。

我检查了连接字符串,看起来很好。如果我取消注释Initializer行,或用SetInitializer(null)替换它,我将得到“模型已更改”错误消息,但事务似乎不是问题。不知何故,它必须与我的自定义迁移器类有关。我在EF 4.3中使用了这个代码并且它有效。在6.1.3中它不再执行。

0 个答案:

没有答案