我在不同的專案中有 DataContext 和 StartUp 類,并在專案中添加新的遷移,Data我使用了以下命令:
dotnet ef migrations add IdentityAdded -s ..\API\API.csproj
這是專案結構:

我剛剛將 ASP.Net Core Identity 添加到基于 .Net 5 的專案中,并將其配置如下:
public class DataContext : IdentityDbContext<AppUser, AppRole, int,
IdentityUserClaim<int>, AppUserRole, IdentityUserLogin<int>,
IdentityRoleClaim<int>, IdentityUserToken<int>>
{
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
ChangeTracker.LazyLoadingEnabled = false;
}
... DbSets
... protected override void OnModelCreating(ModelBuilder modelBuilder)
{ ... }
}
IdentityServiceExtension.cs:
public static class IdentityServiceExtension
{
public static IServiceCollection AddIdentityServices(this IServiceCollection services, IConfiguration configuration)
{
services.AddIdentityCore<AppUser>(opt =>
{
opt.Password.RequireNonAlphanumeric = false;
})
.AddRoles<AppRole>()
.AddRoleManager<RoleManager<AppRole>>()
.AddSignInManager<SignInManager<AppUser>>()
.AddRoleValidator<RoleValidator<AppUser>>()
.AddEntityFrameworkStores<DataContext>();
}
}
我只是繼承了一些類,例如AppUser,AppRole和AppUserRole像這樣的身份類:
public class AppRole : IdentityRole<int>
{
public ICollection<AppUserRole> TheUserRolesList { get; set; }
}
運行遷移后,我收到以下錯誤:
訪問 Microsoft.Extensions.Hosting 服務時出錯。在沒有應用程式服務提供商的情況下繼續。錯誤:無法構造某些服務(驗證服務描述符“ServiceType:Microsoft.AspNetCore.Identity.RoleManager
1[Core.Models.Entities.User.AppRole] Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.RoleManager1[Core.Models.Entities.User.AppRole]”時出錯:實作型別“Microsoft.AspNetCore.Identity. RoleValidator1[Core.Models.Entities.User.AppUser]' can't be converted to service type 'Microsoft.AspNetCore.Identity.IRoleValidator1[Core.Models.Entities.User.AppRole]')
這個實作有什么問題?
uj5u.com熱心網友回復:
您沒有正確注冊,而不是:
.AddRoleValidator<RoleValidator<AppUser>>()
添加:
.AddRoleValidator<RoleValidator<AppRole>>()
您的錯誤指出它無法使用 Core.Models.Entities.User.AppUser 實體化 Microsoft.AspNetCore.Identity.RoleValidator,而是需要 Core.Models.Entities.User.AppRole。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/470990.html
標籤:实体框架 asp.net 核心 实体框架核心 asp.net 身份
上一篇:映射組態檔實體不會創建
