Asp.NET MVC noob here
I have an AppUserRepository
with a task:
public async Task<IEnumerable<AppUser>> GetAllForFirm(Tenant tenant)
{
return await _context.AppUsers.Where(u => u.Tenant == tenant && u.isDeleted == false).ToListAsync();
}
I am then calling this task like so:
ViewModel:
public List<AppUser> UsersForFirm { get; set; }
Controller(AppUserController
):
string username = User.Identity.Name;
AppUser user = await _appUserRepository.GetByUsernameAsync(username);
AppuserViewModel avm = new AppuserViewModel();
avm.UsersForFirm = (List<AppUser>)await _appUserRepository.GetAllForFirm(user.Tenant);
(For extra context, each AppUser
has a 'Tenant' object associated)
This almost works fine, and avm.UsersForFirm
now holds an AppUser
list where a given Tenant
object is associated and I can extract all relevant info like UserNames, Email Addesses, lastLoggedIn dates etc. All good so far...
However, when I try to assign the avm.Id
, it appears as though my GetAllForFirm
task is returning a blank Guid
(00000000-0000-0000-0000-000000000000)
for each AppUser
returned. If I check my database (in the AspNetUsers
table, where all my AppUser
info is stored), all AppUsers
have a valid ('not' blank) Id
and this is the only infomation that differs from the results of the GetAllForFirm()
task.
Is anyone able to explain why this is, and what I'm doing wrong?
Thanks!
CodePudding user response:
Try this and by pass the viewmModel
This is the controller
using Microsoft.AspNetCore.Identity;
using WorkshopPro.Areas.Identity.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
public class UsersAdmin : Controller
{
private UserManager<ApplicationUser> userManager;
private readonly YourContext _cs;
public UsersAdmin(UserManager<ApplicationUser> usrMgr, YourContext cs)
{
userManager = usrMgr;
this.roleManager = roleManager;
_cs = cs;
}
public IActionResult Index()
{
return View(userManager.Users.Where(u => u.Tenant == tenant && u.isDeleted == false).ToList());
}
}
Then under your View
@model IEnumerable<YourProject.Areas.Identity.Data.AppUser>
<table>
@foreach (var item in Model)
{
<tr>
<td></td>
</tr>
}
</table>
CodePudding user response:
In my case it was because I had an Id field in my AppUser.cs
Model.
Removing these lines
public class AppUser : IdentityUser
{
[Key] //<----------- This one
public string Id { get; set; }//<----------- And this one
Is what fixed it for me. After this, many other problems I was having were fixed too, such as User.IsInRole always returning false (and indeed anything else to do with user roles).
I spent 3 whole days trying to work this out, I hope this helps someone else.