簡體   English   中英

無法創建類型為“ApplicationDbContext”的對象。 添加 &#39;IDesignTimeDbContextFactory 的實現<ApplicationDbContext> &#39; 到項目

[英]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 了解設計時支持的其他模式。

啟動文件

`` public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; }

    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();
    }
}``

看看有類似問題的人的這個解決方案 你的依賴注入設置都好嗎? (該清單上的第 2 位)

以下是需要考慮的事項:

您會收到該錯誤,因為要生成遷移,您需要:

  • 帶有默認構造函數(即無參數構造函數)的 DbContext
  • 能夠從 ApplicationServices 獲取 DbContext(即依賴注入)
  • 返回正確配置的 DbContext 的設計時工廠。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM