我已经在代码首次迁移时阅读了每篇博客文章和MSDN文章(http://msdn.microsoft.com/en-us/data/jj591621.aspx),但我不清楚我应该如何使用它。
以下是我项目的迁移历史记录:
Enable-Migrations
,然后使用Add-Migration
和Update-Database
。 add-migration
和update-database
。Disable-Migrations
并运行Enable-Migrations -EnableAutomaticMigration
旧项目(第4步) - 迁移\ Configurations.cs
namespace POC_Manager.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<POC_Manager.Models.POC_ManagerContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
ContextKey = "POC_Manager.Models.POC_ManagerContext";
}
protected override void Seed(POC_Manager.Models.POC_ManagerContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
}
}
}
新项目(第6步) - 迁移\ Configurations.cs
namespace POC_Manager.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<POC_Manager.Models.POC_ManagerContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
ContextKey = "POC_Manager.Models.POC_ManagerContext";
}
protected override void Seed(POC_Manager.Models.POC_ManagerContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
}
}
}
旧项目(步骤#4) - 来自Get-Migrations的输出
PM&GT;获取的迁移 检索已应用于目标数据库的迁移。 201405271907443_AutomaticMigration 201404252210039_InitialCreate
新项目(第6步) - Get-Migrations输出
PM&GT;获取的迁移 检索已应用于目标数据库的迁移。 201407022020263_AutomaticMigration 201406262227296_AutomaticMigration 201405271907443_AutomaticMigration 201404252210039_InitialCreate PM&GT;
另一个令人困惑的部分是......在启用自动迁移后,我是否还需要运行Update-Database命令?
答案 0 :(得分:1)
自动迁移用于根据类的更改自动生成迁移文件;除非您为初始化策略构建逻辑,否则您仍需要运行Update-Database。
就数据丢失而言,它很可能基于您使用的初始化策略。我建议您坚持使用CreateDatabaseIfNotExists,除非您的项目确实需要自定义初始化程序;其他标准的在(早期)开发环境之外并不是非常有用。