EF Core 迁移错误:“无法创建‘ApplicationContext’类型的对象”

Mar*_*rez 11 entity-framework-core asp.net-core

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

PM> add-migration ini
Run Code Online (Sandbox Code Playgroud)

无法创建类型为“ApplicationContext”的对象。将“IDesignTimeDbContextFactory”的实现添加到项目中,或参阅 https://go.microsoft.com/fwlink/?linkid=851728 了解设计时支持的其他模式。

joh*_*ter 9

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

  • 选择主应用程序为我做到了。谢谢你。 (2认同)

Sam*_*Dev 7

我在 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

请参阅有关该主题的这篇博客文章。