SearchโŒ˜ K

Solution: Implement Custom Query with Repository

Explore how to implement custom query methods in repository patterns using ASP.NET Core. Learn to define new interface methods, update mock and SQL repositories, and add new controller endpoints to retrieve user data by name.

Solution

The solution to the challenge is provided below. Feel free to explore the following files:

  • IUserRepo.cs
  • Startup.cs
  • MockUserRepo.cs
  • /Controllers/Api/UsersController.cs
  • SqlUserRepo.cs
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using People.Data;
using People.Models;

namespace People.Controllers.Api
{
    [Route("api/[controller]")]
    [ApiController]
    public class UsersController : ControllerBase
    {
        private readonly IUserRepo _user;

        public UsersController(IUserRepo user)
        {
            _user = user;
        }

        // GET: api/Users
        [HttpGet]
        public IEnumerable<User> GetUsers()
        {
            return _user.GetAllUsers();
        }

        // GET: api/Users/5
        [HttpGet("{id}")]
        public ActionResult<User> GetUser(int id)
        {
            var user = _user.GetUserById(id);

            if (user == null)
            {
                return NotFound();
            }
            return user;
        }

        // PUT: api/Users/5
        [HttpPut("{id}")]
        public IActionResult PutUser(int id, User user)
        {
            if (id != user.ID)
            {
                return BadRequest();
            }
            _user.UpdateUser(user);

            return CreatedAtAction("GetUser", new { id = user.ID }, user);
        }

        // DELETE: api/Users/5
        [HttpDelete("{id}")]
        public ActionResult<User> DeleteUser(int id)
        {
            var user = _user.GetUserById(id);
            if (user == null)
            {
                return NotFound();
            }

            _user.DeleteUser(id);

            return user;
        }

        [Route("name/{name}")]
        [HttpGet]
        public IEnumerable<User> GetUsersByName(string name)
        {
            return _user.GetUsersByName(name);
        }
    }
}
Solution

Click Run to check out the result. After the application has fully launched, click on the link to launch in a new browser tab. Remove /name/neo from the URL to obtain the complete list of users in the database in JSON format. From the output, pick any other name you would like and add /name/{the name you picked} into the URL.

Explanation

IUserRepo.cs

Start off by adding a new function definition to your ...