Search code examples
asp.netasp.net-mvcrazor

How to retrieve data from the database using ASP.NET MVC


I have two models/tables, one is User and the other is role the relationship is one Role can have many users. I am trying to loop through the data in the user model navigation property but i am getting an error that its returning null.

User model

public class User
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int User_Id { get; set; }

    [Required]
    [Display(Name ="User Name")]
    public string User_Name { get; set; }

    [Required(ErrorMessage = "The Field Is Required")]
    [MaxLength(10, ErrorMessage = " Please Enter A Valid Input")]
    public string Password { get; set; }

    //Nav

    [ForeignKey("RoleId")]
    [Display(Name ="User Role:")]
    public int RoleId { get; set;}

    public Role Role { get; set; }
}

Role Model

public class Role
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int  Role_id { get; set; }

    [Required(ErrorMessage ="This field is required")]
    [Display(Name ="Role Name :")]
    public string RoleType { get; set; }
    
    //nav
    public List<User> Users { get; set; }

}

Controller action Method:

public async Task<IActionResult> Index()
        {
            var viewModel = await userRepository.GetAllUsersAlongWithRolesAsync();

            //var viewModel = await baseRepository.GetAllObjectsAsync();

            return View("Index",viewModel);
        }

the Error

Updates: UserRepository that inherited from the IBaseRepository

public class UserRepository : BaseRepository<User>, IUserRepository
{
    private readonly ApplicationDbContext _Context;

    public UserRepository(ApplicationDbContext context):base (context)
    {
        _Context = context;
    }

    public async Task <IEnumerable<User>> GetAllUsersAlongWithRolesAsync()
    {
        var getUsers = await _Context.Users.Include(u => u.Role).ToListAsync();

        return getUsers;
    }
}

In the User controller for injecting:

// injection
private readonly IBaseRepository<User> baseRepository;

private readonly IBaseRepository<Role> roleRepository;

private readonly IUserRepository userRepository;

public UserController(IBaseRepository<User> _baseRepository, IBaseRepository<Role> _roleRepository, IUserRepository userRepository)
{
    baseRepository = _baseRepository;
    this.roleRepository = _roleRepository;
    this.userRepository = userRepository;
}

Solution

  • Since your method GetAllObjectsAsync is so generic, you probably won't be able to add the .Include() you need.

    I'd suggest a separate method GetAllUsers() to your repository - possibly the concrete UserRepository, if you have that:

    public async Task<IEnumerable<User>> GetAllUsersAsync()
    {
        var getUsers = await _Context.Users.Include(u => u.Role).ToListAsync();
    
        return getUsers;
    }