.NET Core 8首次EF迁移报错:服务构造失败+找不到DbContext
问题描述
我有一个包含三个项目的解决方案:
- EmployeeManagement.Database:定义DbContext的类库
- EmployeeManagement.Entities:存放所有实体的类库
- EmployeeManagement.WebAPI:Web API项目
我尝试创建继承自IdentityDbContext的ApplicationDbContext,但在EmployeeManagement.WebAPI项目中执行dotnet ef migrations add InitialMigration命令时出现错误。错误信息包括:
- 访问Microsoft.Extensions.Hosting服务时出错,部分服务无法构造(无法解析
System.TimeProvider、Microsoft.AspNetCore.DataProtection.IDataProtectionProvider) - 在程序集'EmployeeManagement.WebAPI'中未找到DbContext
DbContext代码(EmployeeManagement.Database项目)
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options): base(options) { } public DbSet<ApplicationUser> ApplicationUsers { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { } }
ApplicationUser类(EmployeeManagement.Entities项目)
public class ApplicationUser : IdentityUser { }
Program.cs代码(EmployeeManagement.WebAPI项目)
using EmployeeManagement.Database; using EmployeeManagement.Entities; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; var builder = WebApplication.CreateBuilder(args); // 添加服务到容器 builder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); builder.Services.AddAuthorization(); builder.Services.AddIdentityCore<ApplicationUser>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddApiEndpoints(); var app = builder.Build(); // 配置HTTP请求管道 if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.MapIdentityApi<ApplicationUser>(); app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();
appsettings.json代码(EmployeeManagement.WebAPI项目)
{ "ConnectionStrings": { "DefaultConnection": "Server=localhost;Database=EmployeeManagementDb;Persist Security Info=True;User ID=PPPP;Password=PPPPPP;MultipleActiveResultSets=True;" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*" }
内容的提问来源于stack exchange,提问作者sara
相关产品推荐
相关产品推荐

