EF核心迁移错误:“无法创建类型为'ApplicationContext'的对象”

时间:2018-07-14 20:52:49

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

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

var element = document.querySelector(“example”);
element.addEventListener(“click”,function () {
    var temp = element.style.top.substring(0,element.style.top.length - 2);
    element.style.top = (parseInt(temp) + 5 ) + “px”;
}

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

4 个答案:

答案 0 :(得分:5)

我在asp.net core 3.1上遇到了同样的问题。 对我而言,这很简单,在主要的Web项目中添加了IDesignTimeDbContextFactory的实现即可解决此问题。

基本实现看起来像这样:

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关于该主题的博客文章。

答案 1 :(得分:2)

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

答案 2 :(得分:1)

这很有可能是由于您的默认启动项目:

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

 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进行项目。

答案 3 :(得分:0)

1。使用以下命令在ConfigureService中修改代码:

--profile
  1. 在包含WebApplication.csproj的命令行中:

options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), x => x.MigrationsAssembly("WebApplication")));

相关问题