【发布时间】:2017-12-21 12:59:39
【问题描述】:
我刚刚开始了解 EF6 在更新期间如何运行,并且刚刚弄清楚 AutomaticMigrationsEnabled 的实际作用。我正在尝试使用新的用户表更新数据库。我为用户创建了一个新实体:
[Table("Users")]
public class User
{
<Omitted properties>
}
在我一直从事的项目中,已选择使用显式迁移并且没有任何自动迁移。所以我创建了一个迁移脚本来创建数据库:
public partial class AddingUserTable : DbMigration
{
public override void Up()
{
CreateTable("dbo.Users",.... Omitted for clarity
}
public override void Down()
{
DropTable("dbo.Users");
}
}
并更新我的上下文,以便我可以访问它:
public DbSet<User> Users { get; set; }
此时,如果我在 NuGet 包管理器控制台上执行“更新数据库”,它将应用迁移脚本,但会出现警告:
Applying explicit migration: 201712201003395_AddingUserTable.
Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration.
事实证明,这是因为我将 DBSet 用户添加到了我的上下文中。如果我删除该 DBSet 并再次更新数据库,则不会出现警告。如果我添加它,警告将再次出现。我知道警告是因为我通过添加集合更改了上下文并且我禁用了自动迁移,但我已经通过显式迁移脚本应用了更改。
我需要做什么才能让实体框架看到我已经为它进行了迁移并在没有警告的情况下接受新的 DBSet 用户?
【问题讨论】:
-
如果您再次执行“添加迁移”,它会给您带来什么?
-
@sachin 非常感谢 sachin!事实证明,添加了我不知道它可以做的缺失更改。显然,我在迁移脚本与实体中的属性顺序不匹配。使用自动生成的迁移就像一个魅力。如果你请回答我可以给你的功劳。
-
我已经添加了解决方案作为答案,可能会帮助以后来这里的人
标签: c# entity-framework