Custom IdentityRole in .NET 8

Copper Contributor

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:

Microsoft.Data.SqlClient.SqlException (0x80131904): Invalid column name 'ApplicationRoleId'
 
Can someone help and let me know what I am doing wrong?
 
The final goal is to be able to also inject RoleManager<ApplicationRole> in a controller.
Thanks!
2 Replies

@Stesvisyou could try .AddRoles<ApplicationRole>() in your services:

builder.Services
        .AddIdentity<ApplicationUser, ApplicationRole>()
        .AddRoles<ApplicationRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

 

@PasildaData I eventually removed this from ApplicationRole and the error was gone:

public ICollection<ApplicationUser>? Users { get; set; }