在Entity Framework Code中首次迁移创建数据库

时间:2015-06-02 10:04:47

标签: c# .net entity-framework entity-framework-6.1

在我的项目中,我有两个独立的DbContext。对于一个项目,我有迁移配置,而另一个我没有 - 它只是自动创建数据库。

现在我想创建使用DbMigrator的应用程序并从数据库中删除所有结构并在空数据库中创建它。有我的代码:

public void Install(DatabaseDeployment databaseDeployment)
{
    var migrators = new List<DbMigrator>();
    migrators.Add(this.GetMigrator<DbContext1>(databaseDeployment.ConnectionString));
    migrators.Add(this.GetMigrator<DbContext2>(databaseDeployment.ConnectionString));
    migrators.ForEach(x => x.Update("0"));
    migrators.ForEach(x => x.Update());
}

private DbMigrator GetMigrator<TDbContext>(string connectionString) where TDbContext : DbContext
{
    var configuration = this.FindMigrationsConfiguration<TDbContext>();
    configuration.AutomaticMigrationDataLossAllowed = true;
    configuration.TargetDatabase = new DbConnectionInfo(connectionString, "System.Data.SqlClient");
    var migrator = new DbMigrator(configuration);
    return migrator;
}

private DbMigrationsConfiguration<TDbContext> FindMigrationsConfiguration<TDbContext>() where TDbContext : DbContext
{
    var configurationType =
        AppDomain.CurrentDomain
            .GetAssemblies()
            .SelectMany(assembly => assembly.GetTypes())
            .FirstOrDefault(type => typeof(DbMigrationsConfiguration<TDbContext>).IsAssignableFrom(type));
    if (configurationType != null)
    {
        return (DbMigrationsConfiguration<TDbContext>)Activator.CreateInstance(configurationType);
    }
    else
    {
        return new DbMigrationsConfiguration<TDbContext> { AutomaticMigrationsEnabled = true };
    }
}

不幸的是,它不起作用。第二次更新调用抛出以下SqlException:

Additional information: There is already an object named '__MigrationHistory' in the database.

看起来Entity Framework正在尝试创建它已存在的表dispate。我做错了什么?

0 个答案:

没有答案