I'm currently having problem with displaying a custom object property because the program doesn't seem to insert the associated value from the table with appropriate foreign key. Here are the codes UserViewModel.cs
public class UserViewModel
{
public string Name { get; set; }
public string Id { get; set; }
public Department Department { get; set; }
}
AppUser.cs
public class AppUser : IdentityUser
{
[DefaultValue(null)]
public string Name { get; set; }
public Department Department { get; set; }
public Single1 Single { get; set; }
}
Controller
public async Task<IActionResult> Index()
{
IEnumerable<AppUser> users = await _userRepository.GetAll();
List<UserViewModel> usersViewModel = new List<UserViewModel>();
foreach (var user in users)
{
var userViewModel = new UserViewModel()
{
Id = user.Id,
Name = user.Name,
Department = await _userRepository.GetDepartmentByIdAsync(user.Department.DepartmentId),
};
usersViewModel.Add(userViewModel);
}
return View(usersViewModel);
}
Repository
public async Task<IEnumerable<AppUser>> GetAll()
{
var users = await _context.Users.ToListAsync();
return users;
}
public async Task<Department> GetDepartmentByIdAsync(string id)
{
return await _context.Departments.Where(o => o.DepartmentId == id).FirstOrDefaultAsync();
}
Value I want to be inserted is Department I have foreign key populated
If you need anything else just comment
I tried others null reference exception fixes on google and youtube but nothing worked
Department
information for each user in your view, but you're encountering issues with displaying the associatedDepartment
because the foreign key relationship isn't being correctly inserted into yourAppUser
entity. So you should havepublic string DepartmentId { get; set; }
within appUser class.