C
C#9mo ago
Mawral

Identity/EF collection returns null

Hey, so I'm new to using Entity Framework. I tried to extend the Identity User model with a one-to-many relationship, like so:
//Model/AppUser.cs
public class AppUser : IdentityUser
{
public ICollection<Profile> Profiles { get; }
}

//Model/Profile.cs
public class Profile
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string AppUserId { get; set; }
public AppUser AppUser { get; set; }
}
//Model/AppUser.cs
public class AppUser : IdentityUser
{
public ICollection<Profile> Profiles { get; }
}

//Model/Profile.cs
public class Profile
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string AppUserId { get; set; }
public AppUser AppUser { get; set; }
}
From here, I want to make a razor page that shows a logged in user's 'Profiles' as a list, but going about it the most obvious way gives me a null value. Is there a step I'm missing for getting collection data, or some other error?
//some razor page's cshtml
public async Task<IActionResult> OnGetAsync()
{
StatusMessage = "";
var user = await _userManager.GetUserAsync(User);
if (user == null) {return NotFound($"User ID Not Found");}

Username = user.UserName; //works as expected
Profiles = user.Profiles; //null value
return Page();
}
//some razor page's cshtml
public async Task<IActionResult> OnGetAsync()
{
StatusMessage = "";
var user = await _userManager.GetUserAsync(User);
if (user == null) {return NotFound($"User ID Not Found");}

Username = user.UserName; //works as expected
Profiles = user.Profiles; //null value
return Page();
}
2 Replies
Angius
Angius9mo ago
It's not going to work with the manager. Not unless you make a custom one Related properties are not loaded by default You can just go through the dbcontext
if (User.FindFirstValue(ClaimTypes.NameIdentifier) is not {} uid) return Unauthorized();

var user = await _context.IdentityUsers
.Where(u => u.Id == uid)
.Select(u => new SomeUserDto {
Name = u.UserName,
Profiles = u.Profiles.Select(p => ...)
})
.FirstOrDefaultAsync();

if (user is null) return NotFound();

Username = user.Username;
Profiles = user.Profiles;

return Page();
if (User.FindFirstValue(ClaimTypes.NameIdentifier) is not {} uid) return Unauthorized();

var user = await _context.IdentityUsers
.Where(u => u.Id == uid)
.Select(u => new SomeUserDto {
Name = u.UserName,
Profiles = u.Profiles.Select(p => ...)
})
.FirstOrDefaultAsync();

if (user is null) return NotFound();

Username = user.Username;
Profiles = user.Profiles;

return Page();
Something like this
Mawral
MawralOP9mo ago
I see, thanks a whole bunch
Want results from more Discord servers?
Add your server