Tech Junkie Blog - Real World Tutorials, Happy Coding!: ASP.NET Core: Create The Category Repository

Monday, April 3, 2017

ASP.NET Core: Create The Category Repository

In this post we will create the Category Repository to retrieve information from the database about the the different categories in the NorthwindCafe database.

Here are the steps to create the Category repository class in the NorthwindCafe application:

1.  Create the ICategoryRepository interface for dependency injection, create a file call ICategoryRepository.cs in the "Models" folder with the following code


using System.Collections.Generic;

namespace NorthwindCafe.Web.Models
{
    public interface ICategoryRepository
    {
        IEnumerable GetAllCategories();
        Category GetCategory(int Id);

    }
}


2.  Create the CategoryRepository.cs implementation class and save it in the "Models" folder


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace NorthwindCafe.Web.Models
{
    public class CategoryRepository : ICategoryRepository
    {
        private NorthwindContext _context;

        public CategoryRepository(NorthwindContext context)
        {
            _context = context;   
        }

        public IEnumerable GetAllCategories()
        {
            return _context.Categories.ToList();
        }

        public Category GetCategory(int Id)
        {
            return _context.Categories.Where(c => c.Id == Id).FirstOrDefault();
        }

    }
}



This class basically encapsulate the retrieval methods of the Entity Framework methods. By using the repository pattern the developer calling the method does not care how the data is retrieved they just know that it is retrieving the correct data.

3. Now open the Startup.cs file and type in the following lines of code to add the CategoryRepository class object in the ConfigureServices method services.AddScoped(); The entire ConfigureServices method should look like the following up to this point:


         
public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            var connectionString = Startup.Configuration["Data:NorthwindContextConnection"];
            services.AddDbContext<NorthwindContext>(options => options.UseSqlServer(connectionString));
            services.AddScoped<ICategoryRepository, CategoryRepository>();
            services.AddLogging();
        }

4.  Now to use it in our HomeController all we have to do is inject it into the constructor


using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NorthwindCafe.Web.Models;

// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace NorthwindCafe.Web.Controllers
{
    public class HomeController : Controller
    {
        private ICategoryRepository _categoryRepo;
        private ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger, ICategoryRepository categoryRepo)
        {
            _logger = logger;
            _categoryRepo = categoryRepo;
        }
        // GET: /<controller>/
        public IActionResult Index()
        {
            var categories = _categoryRepo.GetAllCategories();

            return View();
        }
    }
}


If you run the application in debug mode you will see that the Categories have been retrieved from the database using the GetAllCategories method


2 comments:

Search This Blog