[英]ASP.NET WebAPI DbContext - Unable to create an object of type / No database provider has been configured
I've been following this tutorial: YT Tutorial (starts at my issue) with the exception that I'm on .NET6.我一直在关注本教程: YT 教程(从我的问题开始) ,但我使用的是 .NET6。 When I add a migration The two errors I can get are either:
当我添加迁移时我会得到的两个错误是:
Program.cs:程序.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: 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; }
}
ConnectionString:连接字符串:
"ConnectionStrings": {
"DevConnection": "Server=(local)\\sqlexpress;Database=PMRHomeDB;Trusted_Connection=True;MultipleActiveResultSets=True;"
}
Do I need to create a DB first?我需要先创建一个数据库吗? Is this not a code-first EF solution?
这不是代码优先的 EF解决方案吗?
It is not possible to change Services after Build(), so I moved the AddDbContext before it - also leaving out the default constructor in my DbContext class.无法在 Build() 之后更改服务,因此我将 AddDbContext 移到它之前 - 还省略了我的 DbContext class 中的默认构造函数。
string connectionString = builder.Configuration.GetConnectionString("DevConnection");
builder.Services.AddDbContext<PmrDbContext>(options => options.UseSqlServer(connectionString));
var app = builder.Build();
I ran the project and it was working.我运行了这个项目,它正在运行。 Also the Add-Migration also worked this way.
Add-Migration 也以这种方式工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.