【发布时间】:2012-06-30 04:39:03
【问题描述】:
如何在没有 nuget 的情况下迁移数据库?在生产环境中无法将 Visual Studio 与 nuget 一起使用。目前,许多示例仅教我们将 Visual Studio 与 nuget 一起使用。 如何使用生成的 DbMigration 类?
【问题讨论】:
标签: entity-framework ef-code-first entity-framework-migrations
如何在没有 nuget 的情况下迁移数据库?在生产环境中无法将 Visual Studio 与 nuget 一起使用。目前,许多示例仅教我们将 Visual Studio 与 nuget 一起使用。 如何使用生成的 DbMigration 类?
【问题讨论】:
标签: entity-framework ef-code-first entity-framework-migrations
最简单的方法是:
Database.SetInitializer(
new MigrateDatabaseToLatestVersion<MyDbContext,
MyDbMigrationsConfiguration>());
这将在初始化 DbContext 时运行迁移。
您也可以手动强制执行:
var migrator = new DbMigrator(new MyMigrationsConfiguration());
migrator.Update();
(相信你也得在配置上设置TargetDatabase,不过你可以试试)
【讨论】:
以下是选项:
【讨论】:
您可以使用 Web.config 设置迁移到最新版本 - 请参阅 this blog post by Rowan Miller:
如果您使用 Code First 迁移,您可以使用 MigrateDatabaseToLatestVersion 初始化程序将数据库配置为自动迁移。
<contexts>
<context type="Blogging.BlogContext, MyAssembly">
<databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[Blogging.BlogContext,
MyAssembly], [Blogging.Migrations.Configuration, MyAssembly]], EntityFramework" />
</context>
</contexts>
只需在此处交换您的上下文类:System.Data.Entity.MigrateDatabaseToLatestVersion 是 EF 内置的。此设置更新了相同想法的旧 AppSettings 版本。
在我看来这是最好的方法,因为使用哪个初始化器的问题实际上是一个配置问题,并且您希望能够对其进行 Web.config,并理想地应用配置转换以适用于您的不同环境。
【讨论】:
还有另一种解决方案:
Using DB = New SHAContext()
If DB.Database.Exists() Then
Dim migrator As New DbMigrator(New SHAClassLibrary.Migrations.Configuration())
For Each m In migrator.GetDatabaseMigrations()
Try
migrator.Update(m)
Catch ex As Exception
End Try
Next
End If
'DB.test()
End Using
【讨论】:
我一直在寻找一种方法来控制哪些迁移在代码中显式运行,而无需 DbConfiguration 类或启用自动迁移。
所以我设法创建了以下扩展:
public static void RunMigration(this DbContext context, DbMigration migration)
{
var prop = migration.GetType().GetProperty("Operations", BindingFlags.NonPublic | BindingFlags.Instance);
if (prop != null)
{
IEnumerable<MigrationOperation> operations = prop.GetValue(migration) as IEnumerable<MigrationOperation>;
var generator = new SqlServerMigrationSqlGenerator();
var statements = generator.Generate(operations, "2008");
foreach (MigrationStatement item in statements)
context.Database.ExecuteSqlCommand(item.Sql);
}
}
例如,进行如下迁移:
public class CreateIndexOnContactCodeMigration : DbMigration
{
public override void Up()
{
this.CreateIndex("Contacts", "Code");
}
public override void Down()
{
base.Down();
this.DropIndex("Contacts", "Code");
}
}
您可以使用您的 DbContext 运行它:
using (var dbCrm = new CrmDbContext(connectionString))
{
var migration = new CreateIndexOnContactCodeMigration();
migration.Up();
dbCrm.RunMigration(migration);
}
【讨论】: