繁体   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