0

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;
}
9
  • Did you checked the role if that exist? This the screenshot is for view can you please share the related controller details? Commented Jan 7, 2022 at 7:43
  • How (in code) did you load the user to be displayed in that view? Did you use .Include(u => u.Role) to also load the Role object with all its properties? Commented Jan 7, 2022 at 8:04
  • where i suppose to write this line of code and i guess that's the answer Commented Jan 7, 2022 at 8:05
  • @marc_s how can i use your suggestion Commented Jan 7, 2022 at 8:27
  • 1
    Your code is still very much incomplete - can't really tell what you're doing, and what might be the cause for the error. Basically, somewhere you need something like : User myUser = dbContext.User.Where(u => u.Id == id)?.Include(u => u.Role); or something like that - you need to explicitly call .Include to load the dependent property - all the code I've seen so far to does NOT do that and thus your myUser.Role will be NULL .... Commented Jan 7, 2022 at 8:51

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

5 Comments

first thanks so much for your answer and it seems correct but i got another error this is the error title InvalidOperationException: Unable to resolve service for type 'Interfaces.IUserRepository' while attempting to activate 'InventoryManagmentSystem.Controllers.UserController'.
I updated the code can u check it if u got time, i think it's about when i inject IUserRepository
@HeshamEldawy: most likely, you haven't added a service registration for IUserRepository to your startup class (for .NET Core - or whatever DI repo you're using), so the dependency injection system can't find what concrete class to use for IUserRepository when injecting dependencies.
okay i am sorry still didn't get what u are trying to say but what's your recommendation to solve the problem. i injected the IUserRepository correctly i think
@HeshamEldawy: yes, you injected it correctly - but the DI container (either in .NET Core, or any other DI container you might be using) doesn't know about IUserRepository yet. Somewhere, you must be configuring/defining your DI container - there, you need to add the registration for "use UserRepository whenever someone asks for the IUserRepository interface")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.