Asp.net core EF核心迁移错误:“;无法创建类型为';应用上下文'&引用;
我正在尝试使用EF Core进行迁移,但我遇到了一个错误-如何修复此错误Asp.net core EF核心迁移错误:“;无法创建类型为';应用上下文'&引用;,asp.net-core,entity-framework-core,Asp.net Core,Entity Framework Core,我正在尝试使用EF Core进行迁移,但我遇到了一个错误-如何修复此错误 PM> add-migration ini 无法创建“ApplicationContext”类型的对象。添加 “IDesignTimeDbContextFactory”的实现 该项目,或见https://go.microsoft.com/fwlink/?linkid=851728 对于 设计时支持的其他模式 如果您有多个启动项目,也会发生这种情况-迁移时,只需选择一个(在VS右键单击解决方案并设置启动项目…)1。在
PM> add-migration ini
无法创建“ApplicationContext”类型的对象。添加
“IDesignTimeDbContextFactory”的实现
该项目,或见https://go.microsoft.com/fwlink/?linkid=851728 对于
设计时支持的其他模式
如果您有多个启动项目,也会发生这种情况-迁移时,只需选择一个(在VS右键单击解决方案并设置启动项目…)1。在ConfigureService中修改代码,方法是:
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
x => x.MigrationsAssembly("WebApplication")));
dotnet ef migrations add Init
我对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);
}
}
公共类DesignTimeDbContextFactory:IDesignTimeDbContextFactory
{
公共YourDbContext CreateDbContext(字符串[]args)
{
IConfigurationRoot配置=新配置生成器()
.SetBasePath(目录.GetCurrentDirectory())
.AddJsonFile(“appsettings.json”)
.Build();
var builder=new DbContextOptionsBuilder();
var connectionString=configuration.GetConnectionString(“DefaultConnection”);
使用SQLServer(connectionString);
返回新的YourDbContext(builder.Options);
}
}
请参阅有关此主题的博客文章。这很可能是因为您默认的启动项目: 打开Package manager控制台并编写以下命令:
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进行project。您当前用于EF core的版本是什么?请确保您已在Package Manager控制台中选择默认项目(包含DBContext)。在运行上面的命令之前,您已经选择了您的主机项目(它有startup.cs)作为启动项目选择了主应用程序。谢谢。在迁移解决方案中更改启动项目不是一个好主意,最好在PackageManager控制台中通过-StartupProject设置启动项目。