Adding Code to Get Data from Category Table
In this lesson, we're going to add code to get data from Categories table
Adding code to get data from Category table#
We have seeded the data in our database in the last lesson. In this lesson, we will see how to fetch data from our Categories table. Unlike learnings and requirements, we want to call categories separately. Also, we want to see courses that belong to same category. For that, we can create a different controller.
First of all, let's create a new interface inside Interfaces folder which is inside the Entity project and let's call it ICategoryRepository. Inside the interface, the first method will return list of Categories, so we can write Task of type IReadOnlyList of Category and name it GetCategoriesAsync. The second method will return a single Category, so let's make Task of type Category and call it GetCategoryByIdAsync and it will receive an id which will be of type int.
Entity/Interfaces/ICategoryInterface
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Entity.Interfaces
{
public interface ICategoryRepository
{
Task<IReadOnlyList<Category>> GetCategoriesAsync();
Task<Category> GetCategoryByIdAsync(int id);
}
}
Now inside the Infrastructure project, we will have to implement this interface. Let's create a new class called CategoryRepository which will derive from ICategoryRepository. We need to generate a new constructor and use our Store context which will be called context. After this, we will initialize field from parameter. Let's implement this interface now using quick fix.
Let's write our first method, use async and remove this default line and return await context.Categories.ToListAsync()
and that's it. Inside the second method, we need to write async again and remove this line. Let's return await context.Categories.FindAsync(id)
. This is it for the repository. We can now make our Categories controller.
Infrastructure/CategoryRepository.cs
This page is a preview of The newline Guide to Fullstack ASP.NET Core and React