我正在关注 Nick Chapsas 的这个 YouTube 视频,标题为“您必须了解的 .NET 8 Auth 更改!”。我特别卡在时间索引
5:46
试图运行命令dotnet ef migrations add InitialCreate
。
我还尝试使用此页面上的信息合并 OpenApi/Swagger。
我安装了以下 NuGet 包:
这是我的
Program.cs
代码:
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using RpgToolsApi.Models;
using RpgToolsApi.Models.Auth;
using System.Security.Claims;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication().AddBearerToken(IdentityConstants.BearerScheme);
builder.Services.AddAuthorizationBuilder();
builder.Services.AddDbContext<AppDbContext>(x => x.UseSqlite("DataSource=app.db"));
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddIdentityCore<AppUser>()
.AddEntityFrameworkStores<AppDbContext>()
.AddApiEndpoints();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.MapIdentityApi<AppUser>();
app.MapGet("/", (ClaimsPrincipal user) => $"Hello {user.Identity!.Name}!")
.RequireAuthorization();
app.MapPost("/roll", (int Dice, int Sides) => $"Rolling {Dice}d{Sides}...")
.WithName("RollDice")
.WithOpenApi(generatedOperation =>
{
var numDiceParam = generatedOperation.Parameters[0];
numDiceParam.Description = "The number of dice to roll.";
var numSidesParam = generatedOperation.Parameters[1];
numSidesParam.Description = "The number of sides on each die.";
return generatedOperation;
});
app.Run();
我在
AppUser
中还有一个名为 RpgToolsApi.Models.Auth
的空包装类,它继承 IdentityUser
和另一个空包装类,在 AppDbContext
中名为 RpgToolsApi.Models
,它继承 IdentityDbContext
:
using Microsoft.AspNetCore.Identity;
namespace RpgToolsApi.Models.Auth
{
public class AppUser : IdentityUser {}
}
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using RpgToolsApi.Models.Auth;
namespace RpgToolsApi.Models
{
public class AppDbContext : IdentityDbContext<AppUser>
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) {}
}
}
但我收到错误:第 2 行
The type or namespace name 'EntityFrameworkCore' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)
。
因此,
AddDbContext
和 AddEntityFrameworkStores
调用会在第 11 行和第 15 行引发错误。
如何修复错误以便运行迁移并创建数据库?
在 Visual Studio 中右键单击您的解决方案,然后转到 >> 管理 NuGet 包解决方案 >> 搜索包管理器EntityFrameworkCore >> 安装包