无法创建 'ApplicationDbContext' 类型的对象。将 'IDesignTimeDbContextFactory<ApplicationDbContext>' 的实现添加到项目中
Unable to create an object of type 'ApplicationDbContext'. Add an implementation of 'IDesignTimeDbContextFactory<ApplicationDbContext>' to the project
我正在尝试使用 asp.net Core 2.1 创建一个 Angular 8 项目。
每当我尝试使用命令
添加迁移时
cmd 命令:dotnet ef migrations add init --project ../Lgn.DAL
终端抛出错误:
无法创建 'ApplicationDbContext' 类型的对象。将 'IDesignTimeDbContextFactory' 的实现添加到项目中,或查看 https://go.microsoft.com/fwlink/?linkid=851728 了解设计时支持的其他模式。
Startup.cs
``
public class 启动
{
public Startup(IConfiguration配置)
{
配置=配置;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseCors(builder =>
{
builder.WithOrigins("http://localhost:4200");
builder.AllowAnyMethod();
builder.AllowAnyHeader();
});
app.UseHttpsRedirection();
app.UseMvc();
}
}``
看看 this solution 给有类似问题的人。你的依赖注入设置好吗? (该列表中的第 2 位)
以下是需要考虑的事项:
您收到该错误是因为要生成迁移,您需要:
- 具有默认构造函数(即无参数的
构造函数)
- 能够从 ApplicationServices 获取 DbContext
(也就是依赖注入)
- returns 一个设计时工厂
正确配置 DbContext。
我正在尝试使用 asp.net Core 2.1 创建一个 Angular 8 项目。 每当我尝试使用命令
添加迁移时cmd 命令:dotnet ef migrations add init --project ../Lgn.DAL
终端抛出错误: 无法创建 'ApplicationDbContext' 类型的对象。将 'IDesignTimeDbContextFactory' 的实现添加到项目中,或查看 https://go.microsoft.com/fwlink/?linkid=851728 了解设计时支持的其他模式。
Startup.cs
`` public class 启动 { public Startup(IConfiguration配置) { 配置=配置; }
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseCors(builder =>
{
builder.WithOrigins("http://localhost:4200");
builder.AllowAnyMethod();
builder.AllowAnyHeader();
});
app.UseHttpsRedirection();
app.UseMvc();
}
}``
看看 this solution 给有类似问题的人。你的依赖注入设置好吗? (该列表中的第 2 位)
以下是需要考虑的事项:
您收到该错误是因为要生成迁移,您需要:
- 具有默认构造函数(即无参数的 构造函数)
- 能够从 ApplicationServices 获取 DbContext (也就是依赖注入)
- returns 一个设计时工厂 正确配置 DbContext。