Nov 29 2023 07:32 PM
I am working on a .NET 8 API project and I had to customize the IdentityRole to add an extra column Order, so I created a custom ApplicationRole class:
public class ApplicationRole : IdentityRole
{
public ApplicationRole() : base()
{
}
public ApplicationRole(string name) : base(name)
{
}
public ApplicationRole(string name, int order) : base(name)
{
this.Order = order;
}
public virtual int Order { get; set; }
public ICollection<ApplicationUser>? Users { get; set; }
}
Now my understanding is that I have to use this new class in Program.cs:
builder.Services
.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
And in my ApplicationDbContext:
public partial class ApplicationDbContext
: IdentityDbContext<ApplicationUser, ApplicationRole,string>
{
//...
}
At this point I get exceptions every time I want to use the UserManager injected in my ApiController:
public class AuthControler : ControllerBase
{
public UserManager<ApplicationUser> UserManager { get; }
public AuthController(UserManager<ApplicationUser> userManager)
{
UserManager = userManager;
}
public async Task<ActionResult> Test(string username)
{
var user = await UserManager.FindByNameAsync(username);
return Ok(user);
}
}
The exception I get is:
Dec 01 2023 03:58 AM
@Stesvisyou could try .AddRoles<ApplicationRole>() in your services:
builder.Services
.AddIdentity<ApplicationUser, ApplicationRole>()
.AddRoles<ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
Dec 04 2023 11:16 AM
@PasildaData I eventually removed this from ApplicationRole and the error was gone:
public ICollection<ApplicationUser>? Users { get; set; }