I'm using ASP.NET Core 2.1 Identity. I've overridden IdentityUser because I need to add some additional properties on the user.
In Startup.cs
services.AddDefaultIdentity<PortalUser>().AddEntityFrameworkStores<ApplicationDbContext>();
ApplicationDbContext.cs
public partial class ApplicationDbContext : IdentityDbContext<PortalUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
}
PortalUser class
public class PortalUser : IdentityUser
{
[PersonalData]
public DateTime? LastLoginDateUtc { get; set; }
[PersonalData]
public DateTime? RegistrationDateUtc { get; set; }
}
That's all working fine. I can add a user via.
_userManager.CreateAsync(user)
However, when I call AddToRolesAsync to add a role to a user, I'm getting an exception. Any ideas why?
_userManager.AddToRolesAsync(user, new List<string> { roleName });
{System.NotSupportedException: Store does not implement IUserRoleStore<TUser>.
at Microsoft.AspNetCore.Identity.UserManager`1.GetUserRoleStore()
at Microsoft.AspNetCore.Identity.UserManager`1.AddToRolesAsync(TUser user, IEnumerable`1 roles)}
In Startup.cs, I was missing AddRoles so
services.AddDefaultIdentity<PortalUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();
should be
services.AddDefaultIdentity<PortalUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
Note: The order is critical. AddRoles
must come before AddEntityFrameworkStores