c# - Entity Framework ,自动应用迁移

标签 c# entity-framework ef-code-first entity-framework-migrations

我正在使用 Entity Framework Code First 方法和 AutomaticMigrationsEnabled = true:

Database.SetInitializer(new MigrateDatabaseToLatestVersion<DbContext, MigrateDBConfiguration>());
//////////////////////////////////

public class MigrateDBConfiguration : System.Data.Entity.Migrations.DbMigrationsConfiguration<DbContext>
{
    public MigrateDBConfiguration()
    {
        AutomaticMigrationsEnabled = true;
        AutomaticMigrationDataLossAllowed = true;
    }
}

项目的第一次运行会按预期创建数据库和表。通过添加或删除字段更改模型后,我运行了 Add-Migration。生成了 Migration 类,但在运行项目后出现此异常:

An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code

Additional information: The model backing the 'DBContext' context has changed since the database was created.

编辑:根据 arturo menchaca 的答案中的指导我这样更改了我的代码:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<DBContext, MigrateDBConfiguration<DBContext>>());

...

更改后发生此异常:

There is already an object named 'MyTable' in the database.

如何应用我的数据库迁移?

最佳答案

Automatic Migrations 意味着您不需要为模型中的更改运行 add-migration 命令,但您必须运行 update-database 手动命令。

如果在调用 update-database 时启用了Automatic Migrations,如果模型中有待处理的更改,将添加“自动”迁移并更新数据库已更新。

如果您希望更新数据库而不需要调用 update-database 命令,您可以在 OnModelCreating 中添加 Database.SetInitializer(...) () 方法在你的上下文中,像这样:

public class MyContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, MigrateDBConfiguration>());
    }

    ...
}

public class MigrateDBConfiguration : System.Data.Entity.Migrations.DbMigrationsConfiguration<MyContext>
{
    ...

请注意,您应该使用您的真实上下文声明 DbMigrationsConfigurationMigrateDatabaseToLatestVersion,而不是默认的 DbContext

关于c# - Entity Framework ,自动应用迁移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36265827/

相关文章:

c# - 动态添加的 TableRows 不在 Postback 的 Rows 集合中

c# - 手动创建 IWebHostEnvironment asp.net core 3.1

entity-framework - Entity Framework - DRY 查询

asp.net-mvc - 架构决策 : ASP. NET MVC 和 Entity Framework

entity-framework - ASP.NET-Identity:如何限制用户名长度?

c# - 如何使用 Angular 和 ASP.Net Core 转换字节数组 [] 中的文件并存储在数据库中?

C# foreach 抽象的子级

asp.net-mvc - 如何在 ASP.NET MVC 和 Entity Framework 中扩展模型?

c# - 在 DropCreateDatabaseIfModelChanges 删除数据库之前进行备份

c# - 我可以使用 Entity Framework Code First 指定子实体默认排序吗?