ASP.NET Core 7.0中用PostgreSQL DbContext添加Identity脚手架失败
解决Identity脚手架不识别PostgreSQL的问题
1. 先把连接字符串改对
EF Core搭配Npgsql时,根本不需要Provider和Driver参数,直接用标准PostgreSQL连接字符串格式修改appsettings.json:
"ConnectionStrings": { "DefaultConnection": "Host=你的主机地址;Database=你的数据库名;Username=postgres;Password=你的密码;Pooling=true;" }
2. 别让DbContext重复配置
你的ApplicationDbContext里的OnConfiguring方法会覆盖Program.cs的配置,导致脚手架识别混乱。改成仅当外部未配置时才生效:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { // 只有Program.cs没配置DbContext时才用这里的设置 if (!optionsBuilder.IsConfigured) { var connectionString = _configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found."); optionsBuilder.UseNpgsql(connectionString); } }
另外,构造函数可以简化,直接依赖传入的DbContextOptions即可,避免多余依赖:
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { // 数据库初始化逻辑保留不变 try { var databaseCreator = Database.GetService<IDatabaseCreator>() as RelationalDatabaseCreator; if (databaseCreator != null) { if (!databaseCreator.CanConnect()) { databaseCreator.Create(); } if (!databaseCreator.HasTables()) { databaseCreator.CreateTables(); } } } catch (Exception ex) { Console.WriteLine(ex.Message); } }
3. 补全Identity服务绑定
Program.cs里得明确把Identity和你的ApplicationDbContext绑定,不然脚手架找不到对应的存储提供器:
// 放在AddDbContextFactory之后添加 builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores<ApplicationDbContext>();
4. 清掉VS的缓存垃圾
Visual Studio的缓存偶尔会抽风,按以下步骤清理:
- 关闭Visual Studio
- 删除项目根目录下的
.vs隐藏文件夹(需开启显示隐藏文件) - 删除
bin和obj文件夹 - 重新打开项目,右键项目选择「还原NuGet包」
5. 用命令行绕开UI问题
如果UI还是不识别,直接用命令行生成脚手架。打开Package Manager Console,运行(把YourNamespace替换成你的项目命名空间):
# 生成指定的Identity页面(比如登录、注册) dotnet aspnet-codegenerator identity -dc YourNamespace.ApplicationDbContext --files Account.Login,Account.Register
要生成所有Identity页面就用:
dotnet aspnet-codegenerator identity -dc YourNamespace.ApplicationDbContext --all
6. 检查项目包引用
打开.csproj文件,确保没有SQL Server相关包,只保留以下对应版本的依赖(版本需和你的.NET版本匹配,比如.NET 7就用7.x版本):
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.4" /> <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL.Design" Version="7.0.4" /> <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="7.0.5" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.5" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.5" />
内容的提问来源于stack exchange,提问作者Steven Edison
相关产品推荐
相关产品推荐

