Net Core Identity one role per user

.net-core asp.net-core-identity c# entity-framework-core

Question

I want to have only one MyIdentityRole per MyIdentityUser. My Current Code:

public class MyIdentityUser: IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Image { get; set; }
    public string PersonalNumber { get; set; }
    public string Address { get; set; }
    public bool IsDeleted { get; set; }
    public string MyIdentityRoleId { get; set; }
    public MyIdentityRole MyIdentityRole { get; set; }
}

public class MyIdentityRole: IdentityRole
{
    public List<MyIdentityUser> MyIdentityUsers { get; set; }
    public List<MenuPermission> MenuPermissions { get; set; }
}

Controller side Code:

private readonly UserManager<MyIdentityUser> _UserManager;
public AdminSideMenuViewComponent(IMenuService menuService, UserManager<MyIdentityUser> userManager)
{
  this._MenuService = menuService;
  this._UserManager = userManager;
}
public async Task<IViewComponentResult> InvokeAsync()
{
  var user = await _UserManager.GetUserAsync(HttpContext.User);
  var role = user?.MyIdentityRole; // is always null
  var roleId = user?.MyIdentityRoleId; // returns actual roleId as it should
}

A small problem is that when I get a user with RoleManager everything is filled correctly, but navigation property MyIdentityRole in MyIdentityUser is always NULL though MyIdentityRoleId shows correct role Id. In database [dbo].[AspNetUsers] has a foreign key MyIdentityRoleId generated by codefirst migration.

Am I doing something wrong?

1
1
2/24/2020 4:03:20 PM

Accepted Answer

but navigation property MyIdentityRole in MyIdentityUser is always NULL though MyIdentityRoleId shows correct role Id.

Try this:

var username = HttpContext.User.Identity.Name;
var user = await _userManager.Users.Include(u => u.MyIdentityRole)
                                   .Where(u => u.UserName == username).FirstOrDefaultAsync();
var roles = user?.MyIdentityRole; 
var roleId = user?.MyIdentityRoleId;

Result: enter image description here Another simple way:

var role = User.FindAll(c => string.Equals(c.Type, ClaimTypes.Role)).First().Value;
1
2/26/2020 8:37:36 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow