![](/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.