gpt4 book ai didi

entity-framework - 在禁用自动迁移的 Entity Framework 6 中自动创建数据库

转载 作者:行者123 更新时间:2023-12-01 11:32:07 26 4
gpt4 key购买 nike

我希望能够自动创建一个新数据库,如果它不存在,使用代码优先 EF6 但禁用自动迁移。

如果我没记错的话,在 Entity Framework 中存在自动迁移之前,这工作得很好。但是,在 EF6 中,我收到以下异常:

An exception of type 'System.Data.Entity.Migrations.Infrastructure.AutomaticMigrationsDisabledException' occurred in EntityFramework.dll but was not handled in user code

Additional information: 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.



为了验证这个异常不是由我的生产项目中的外部因素引起的,我创建了一个新的测试项目。但是,我得到了同样的异常(exception)。

对于我的数据库上下文,我有:
public class MyContext : DbContext
{
public DbSet<Entity> Entities { get; set; }

public MyContext()
{
Database.SetInitializer(new CreateDatabaseIfNotExists<MyContext>());
}
}

然后我添加了一个数据库迁移配置文件来禁用自动迁移:
public class DatabaseConfiguration : DbMigrationsConfiguration<MyContext>
{
public DatabaseConfiguration()
{
this.AutomaticMigrationsEnabled = false;
}
}

如果一个新数据库不存在,我只需要能够创建一个新数据库(这样我就可以快速删除并重新创建一个新数据库,以便在我的开发机器上进行快速开发)。但是,我不想启用自动迁移,因为我们在生产中使用 3rd 方工具进行迁移,如果启用自动迁移时架构发生更改,EF6 会提示。

任何解决这些需求的见解或替代选择将不胜感激。谢谢!

最佳答案

也许你可以...

  • 将数据库初始化程序设置为 null(以禁用模型兼容性检查)
    public class MyContext : DbContext
    {
    static MyContext()
    {
    Database.SetInitializer<MyContext>(null);
    }
    }
  • 明确调用 MyContext.Database.CreateIfNotExists() 在您选择的适当时间。


  • 编辑

    如果您没有使用 Code First 迁移,您似乎需要删除 DbMigrationsConfiguration :

    At run time, Code First looks for a DbMigrationsConfiguration class that’s tied to a context when that context goes through its data­base initialization process. If that class is found, any explicit calls or settings to set database initialization to any of the original three initializers—whose job is to create or drop and create the database—will create the database using the migrations.



    https://msdn.microsoft.com/en-us/magazine/dn818489.aspx

    我认为即使您不使用初始化程序,它也必须做同样的事情。

    关于entity-framework - 在禁用自动迁移的 Entity Framework 6 中自动创建数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31409860/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com