如何使用 ASP.NET MVC 从数据库中检索数据

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

我有两个models/tables,一个是User,一个是role,关系是一个Role可以有很多用户。我正在尝试循环访问用户模型导航中的数据 属性 但我收到一个错误,它返回 null。

用户模型

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; }
}

榜样

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; }

}

控制器动作方法:

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

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

            return View("Index",viewModel);
        }

更新UserRepository继承自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;
    }
}

在用于注入的用户控制器中:

// 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;
}

由于您的方法 GetAllObjectsAsync 过于通用,您可能无法添加所需的 .Include()

我会向您的存储库建议一个单独的方法 GetAllUsers() - 可能是具体的 UserRepository,如果您有的话:

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

    return getUsers;
}