簡體   English   中英

ASP.NET WebAPI DbContext - 無法創建 object 類型/未配置數據庫提供程序

[英]ASP.NET WebAPI DbContext - Unable to create an object of type / No database provider has been configured

我一直在關注本教程: YT 教程(從我的問題開始) ,但我使用的是 .NET6。 當我添加遷移時我會得到的兩個錯誤是:

  • 沒有為此 DbContext 配置數據庫提供程序 (...)
  • 無法創建“PmrDbContext”類型的 object。 (...) <- 如果我遺漏默認構造函數,就會發生這種情況

程序.cs:

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var app = builder.Build();
string connectionString = builder.Configuration.GetConnectionString("DevConnection");
builder.Services.AddDbContext<PmrDbContext>(options => options.UseSqlServer(connectionString));

PmrDbContext.cs:

public class PmrDbContext : DbContext
{
    // default constructor there - one or the other error

    public PmrDbContext(DbContextOptions<PmrDbContext> options) : base(options)
    {

    }

    public DbSet<Employee> Employees { get; set; }
}

連接字符串:

"ConnectionStrings": {
  "DevConnection": "Server=(local)\\sqlexpress;Database=PMRHomeDB;Trusted_Connection=True;MultipleActiveResultSets=True;"
 }

我需要先創建一個數據庫嗎? 這不是代碼優先的 EF解決方案嗎?

無法在 Build() 之后更改服務,因此我將 AddDbContext 移到它之前 - 還省略了我的 DbContext class 中的默認構造函數。

string connectionString = builder.Configuration.GetConnectionString("DevConnection");
builder.Services.AddDbContext<PmrDbContext>(options => options.UseSqlServer(connectionString));
var app = builder.Build();

我運行了這個項目,它正在運行。 Add-Migration 也以這種方式工作。

暫無
暫無

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

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