Search code examples
c#asp.net-mvcasp.net-core.net-6.0

How to insert a custom object into an User using foreign key


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


Solution

  • 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

    Based on your code and description along with the screenshot, you're having trouble displaying Department information for AppUsers because of an issue with how user department data is being stored.

    I have tried to investigate your issue, and you could follow the step below if you want to get the department associated with the AppUser.

    When creating or updating an AppUser, ensure that you set the DepartmentId property to the corresponding Department's primary key (DepartmentId).

    Apart from that, make sure that AppUser and Department have a proper one-to-many or many-to-one relationship defined in your database context.

    Let's have a look at the implementation, how we could achieve that:

    Model:

    public class AppUser : IdentityUser
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string DepartmentId { get; set; }
        public Department Department { get; set; }
    }
    
    public class Department
    {
        [Key]
        public string DepartmentId { get; set; }
        public string DepartmentName { get; set; }
    
    }
    

    ViewModel:

    public class UserViewModel
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public Department Department { get; set; }
    }
    

    Repository:

    public async Task<IEnumerable<AppUser>> GetAllWithDepartmentsAsync()
     {
         var users = await _context.Users
             .Include(u => u.Department)
             .ToListAsync();
    
         
         var appUsers = users.Select(u => new AppUser
         {
             Id = u.Id,
             Name = u.UserName,
             Department = u.Department,
            
         });
    
         return appUsers;
     }
    

    Controller:

    public async Task<IActionResult> Index()
    {
        var users = await _userRepository.GetAllWithDepartmentsAsync();
        var usersViewModel = users.Select(user => new UserViewModel
        {
            Id = user.Id,
            Name = user.Name,
            Department = user.Department
        }).ToList();
    
        return View(usersViewModel);
    }
    

    View:

    @model List<UserViewModel>
    
    <table class="table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Department</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var user in Model)
            {
                <tr>
                    <td>@user.Id</td>
                    <td>@user.Name</td>
                    <td>@user.Department.DepartmentName</td>
                </tr>
            }
        </tbody>
    </table>
    

    Output:

    enter image description here

    enter image description here

    enter image description here

    enter image description here

    enter image description here

    Note: If you want to learn more details about entity relationship, you could refer to this official document.