I have a method that gets all the users that i have in my db, simply put i do this:
var allUsers = context.Users.ToList();
What i can't figure it out is that when i debug the roles property it is empty:
but in dbo.UserRoles:
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 getting the roles like this:
var roles = context.Roles.ToList();
I can see all the roles and I can also see which users have the specific role:
EDIT 3:
Tried turning lazyloading off and on
this.Configuration.LazyLoadingEnabled = true;
this.Configuration.LazyLoadingEnabled = false;
Still doesn't give me the roles data.
You have to load related entities you want to use with Include like this :
var allUsers = context.Users.Include(u => u.Roles).ToList();
Then you should be able to access user roles.
More info about that topic here
So far I have not been able to solve this they way I want. I made a work arround that works:
I created a method that got me each individual user role like so:
public string GetRole(string userId)
{
var role = UserManager.GetRoles(userId);
return role[0];
}
and in my original Getuser method i called the my recently developed method:
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;
}
This gives me the data I want but I consider this a dirty fix and I hope someone out there has a proper solution to the problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With