尝试使用所有代码来获得所有具有其角色的用户,所以我不得不稍微修改一下代码并遇到此错误。我不确定自己做错了什么,我将其范围缩小到了startup.cs和ApplicationDBContect
类。我没有任何错误,并且可能需要进行迁移,但是这样做并没有阻止引起更多问题。
我引用了Stackoverflow question,并且还有其他错误。
ApplicationDBContext.cs
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserClaim<string>,
ApplicationUserRole, IdentityUserLogin<string>,
IdentityRoleClaim<string>, IdentityUserToken<string>>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<ApplicationUserRole>(userRole =>
{
userRole.HasKey(ur => new { ur.UserId, ur.RoleId });
userRole.HasOne(ur => ur.Role)
.WithMany(r => r.UserRoles)
.HasForeignKey(ur => ur.RoleId)
.IsRequired();
userRole.HasOne(ur => ur.User)
.WithMany(r => r.UserRoles)
.HasForeignKey(ur => ur.UserId)
.IsRequired();
});
}
public DbSet<ApplicationUser> ApplicationUser { get; set; }
}
Startup.cs
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultUI()
.AddDefaultTokenProviders();
答案 0 :(得分:2)
我看到您分别用IdenityUser
和IdentityRole
扩展了ApplicationUser
和ApplicationRole
,但是您没有将它们添加到身份服务注册中。因此,请按照以下步骤在启动时更新您的身份服务注册:
services.AddIdentity<ApplicationUser, ApplicationRole>() // </-- here you have to replace `IdenityUser` and `IdentityRole` with `ApplicationUser` and `ApplicationRole` respectively
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultUI()
.AddDefaultTokenProviders();