【问题标题】:EF Core Migration error: "Unable to create an object of type 'ApplicationContext'"EF Core 迁移错误:“无法创建‘ApplicationContext’类型的对象”
【发布时间】:2021-11-25 19:24:10
【问题描述】:

我正在尝试使用 EF Core 进行迁移,但出现错误 - 如何修复此错误?

PM> add-migration ini

无法创建“ApplicationContext”类型的对象。添加一个 'IDesignTimeDbContextFactory' 的实现 该项目,或查看 https://go.microsoft.com/fwlink/?linkid=851728 设计时支持的其他模式。

【问题讨论】:

  • 您目前使用的 EF 核心版本是什么?
  • 确保您在包管理器控制台中选择了默认项目(具有 DBContext)。在运行上述命令之前,您已经选择了您的宿主项目(包含 startup.cs)作为启动项目

标签: asp.net-core entity-framework-core


【解决方案1】:

如果您有多个启动项目,也会发生这种情况 - 迁移时,只需选择一个(在 VS 中右键单击解决方案并设置启动项目...)

【讨论】:

  • 选择主应用程序为我做了。谢谢。
  • 在迁移解决方案中更改启动项目不是一个好主意,最好通过 -StartupProject 在包管理器控制台中设置启动项目。
【解决方案2】:

我在使用 asp.net core 3.1 时遇到了同样的问题。 对我来说,这很简单,将IDesignTimeDbContextFactory 的实现添加到主 Web 项目解决了这个问题。

基本实现如下所示:

public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<YourDbContext>
{
    public YourDbContext CreateDbContext(string[] args)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();
        var builder = new DbContextOptionsBuilder<YourDbContext >();
        var connectionString = configuration.GetConnectionString("DefaultConnection");
        builder.UseSqlServer(connectionString);
        return new YourDbContext(builder.Options);
    }
}

请参考this关于该主题的博文。

【讨论】:

    【解决方案3】:

    很可能是因为你的默认启动项目:

    打开包管理器控制台并编写以下命令:

     PM> Add-Migration -StartupProject[YourProjectPath(just press a tab all the.csproj paths will come up, and then choose your DataBaseLayer project to execute a migration for)] migrationName
    

    这样你就不需要再去解决方案和设置启动 每当您完成添加新迁移时,使用您的 webProject 进行项目。

    【讨论】:

      【解决方案4】:

      1.在 ConfigureService 中修改您的代码:

      options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
      
              x => x.MigrationsAssembly("WebApplication")));
      
      1. 在包含 WebApplication.csproj 的命令行中:

      dotnet ef migrations add Init

      【讨论】:

        【解决方案5】:

        创建迁移时出现此错误。在 ApplicationContext 构造函数的代码中,我使用了 Database.EnsureCreated() 方法。通常,此方法用于需要检查数据库是否存在并创建一次的小型应用程序。在使用会随新版本更改的数据库创建应用程序并使用迁移时,您不应使用此方法。

        【讨论】:

          【解决方案6】:

          就我而言,存在此错误是因为我是 applying migrations at runtime。在我的代码中删除 Database.Migrate(); 后,我能够毫无错误地添加新的迁移。

          顺便说一句,我使用的是EF Core .NET command-line interface (CLI) tools,而不是包管理器控制台(我在使用包管理器控制台时遇到了无法解决的问题,所以我选择了 CLI 替代方案,值得改变)。

          另外,请确保使用the appropriate options 选择your startup project and your target project

          【讨论】:

            猜你喜欢
            • 2021-02-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-04-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多