Identity: Why is user.roles empty?

I have a method that gets all the users that I have in my db, just put this:

var allUsers = context.Users.ToList();

What I cannot understand is that when I debug the role property, it is empty:

enter image description here

but in dbo.UserRoles:

enter image description here

What am I missing here?

EDIT:

My registration method:

    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                UserManager.AddToRole(user.Id, model.UserRole.ToString());

                return RedirectToAction("Index", "Home");                 
            }
            AddErrors(result);
        }

        // If we got this far, something failed, redisplay form
        return PartialView("~/Views/Account/Register.cshtml",model);
    }

EDIT 2:

When creating such roles:

var roles  = context.Roles.ToList();

I can see all the roles, and I can also see which users have a specific role:

enter image description here

EDIT 3:

Tried turning off and off lazyloading

 this.Configuration.LazyLoadingEnabled = true;

 this.Configuration.LazyLoadingEnabled = false;

Still not giving me role data.

+4
source share
2 answers

Until now, I could not solve it the way I want. I did a job that works:

, :

    public string GetRole(string userId)
    {
        var role = UserManager.GetRoles(userId);

        return role[0];
    }

Getuser :

    public UserModel GetUsers()
    {
       var allUsers = context.Users.Include("Roles").ToList();

       var model = new UserModel
         {
            Users = allUsers.Select(x => new OverWatchUser
            {
                Email = x.Email,
                EmailConfirmed = x.EmailConfirmed,
                FirstName = x.FirstName,
                LastName = x.LastName,
                OrgId = x.OrgId,
                Role = GetRole(x.Id)

            }).ToList()

        };

        return model;
    }

, , , , - .

0

, Include, :

var allUsers = context.Users.Include(u => u.Roles).ToList();

.

+2

Source: https://habr.com/ru/post/1652320/


All Articles