![](/img/trans.png)
[英]ASP.NET API: No database provider has been configured for this DbContext
[英]ASP.NET WebAPI DbContext - Unable to create an object of type / No database provider has been configured
我一直在關注本教程: YT 教程(從我的問題開始) ,但我使用的是 .NET6。 當我添加遷移時我會得到的兩個錯誤是:
程序.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.