Hi @Joachim Petersen ,
By default, the Identity User and Identity Role's id property are GUID type, there is no need to override it to GUID type again in the ApplicationRole's constructor method. More detail information, see Identity model customization in ASP.NET Core.
await roleManager.CreateAsync(new IdentityRole("hey")); // ERROR: Argument 1: cannot convert from 'Microsoft.AspNetCore.Identity.IdentityRole' to 'AspNetCore.Identity.Custom.Models.ApplicationRole'
About this error, since you have already configured the Identity use custom ApplicationRole
model, when register the RoleManager and create new Role, you should use the ApplicationRole
model, instead of IdentityRole
.
You can refer the following sample to add custom role data to Identity in an ASP.NET Core project.
ApplicationRole.cs:
public class ApplicationRole:IdentityRole
{
public DateTime CreateDate { get; set; }
}
ApplicationDbContext.cs
public class ApplicationDbContext : IdentityDbContext
{
public DbSet<ApplicationUser> ApplicationUsers { get; set; }
public DbSet<ApplicationRole> ApplicationRoles { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
}
Configure the Identity in the ConfigureServices method:
services.AddIdentity<ApplicationUser, ApplicationRole>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders()
.AddDefaultUI();
Add RoleController with the following code: Here we should use the ApplicationRole model, instead of IdentityRole model.
public class RoleController : Controller
{
private readonly RoleManager<ApplicationRole> _roleManager;
private readonly ApplicationDbContext dbcontext;
public RoleController(RoleManager<ApplicationRole> roleManager, ApplicationDbContext db)
{
_roleManager = roleManager;
dbcontext = db;
}
public IActionResult Index()
{
var roles = _roleManager.Roles.ToList();
return View(roles);
}
public IActionResult Create()
{
return View(new ApplicationRole());
}
[HttpPost]
public async Task<IActionResult> Create(ApplicationRole role)
{
role.CreateDate = DateTime.Now;
await _roleManager.CreateAsync(role);
return RedirectToAction("Index");
}
}
The result as below:
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion