Tech Junkie Blog - Real World Tutorials, Happy Coding!: Hour 15 AspNet.Core Use Repository Pattern To Show Poducts

Monday, August 26, 2019

Hour 15 AspNet.Core Use Repository Pattern To Show Poducts

Now that we have our data in the database it is time for us to show the data to our users and we going to use the repository pattern to show our data.  A repository pattern is basically a conduit between the database and our business objects that has built in CRUD operations.  It is ideal for LOB applications.  There are many websites and books that explains the repository pattern better than I do.  Feel free to explore them.

Here are the steps to create a product repository for the products in the database:

1. Create a folder in the NorthwindCafe.Web solution call "Data"
2. Create an interface call IProductRepository in the "Data" folder, this will be the interface that we implement our repository from.

The code of the IProductRepository should look like this

using NorthwindCafe.Web.Models;
using System.Collections.Generic;

namespace NorthwindCafe.Web.Data
{
    public interface IProductRepository
    {
        IEnumerable<Product> GetProducts();
    }
}



As you can currently there's only one method and that's the GetProducts method that returns an enumerable of Products.  Let's keep it simple for now.

3.  Now we want to implement the interface with the ProductRepository class.  Here is how the ProductRepository class looks like

using NorthwindCafe.Web.Models;
using System.Collections.Generic;
using System.Linq;

namespace NorthwindCafe.Web.Data
{
    public class ProductRepository : IProductRepository
    {
        private readonly NorthwindContext _context;

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

        public IEnumerable<Product> GetProducts()
        {
            return _context.Products.OrderBy(p => p.Name).ToList();
        }
    }
}

What code above does is basically injecting the NorthwindContext object into the constructor of the ProductRepository so that we can use throughout the class and use to get the Products from the database using Entity Framework in the GetProducts method.

4.  Now we are at the final step which is where the magic happens, we are going to the map the interface to the implementation of the ProductRepository in the Startup.cs file.  So open up the Startup.cs file and type in the following code in the ConfigureServices method

services.AddScoped<IProductRepository, ProductRepository>();

AddScoped adds the mapping between IProductRepository to the ProductRepository.  If you have a mockup of the repository this is where you would make the switch.  AddScoped adds the object that's the same within the same request, which is what we want.

Your 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<IProductRepository, ProductRepository>();
        }

5. Now that we've set up all the plumbing it's time to use the repository in our controller. Open the HomeController in the "Controllers" folder. 6. Create a readonly private variable call _repository and then create a HomeController constructor with the NorthwindContext injected into it, the code should look like the following.
        private readonly IProductRepository _repository;

        public HomeController(IProductRepository repository)
        {
            _repository = repository;
        }
7. Now we are going to call the GetProducts method in the repository and return it in the Index view
        public IActionResult Index()
        {
            var products = _repository.GetProducts();

            return View(products);
        }
8. Build the solution and run it in debug mode, you should see that data is coming through from the database.


















githubhttps://github.com/techjunkiejh/NorthwindCafe/tree/Hour15

Previous: Hour 14 ASP.NET Core: Seeding The NorwindCafe Database
Next: Hour 16: ASP.NET Core Display Products

3 comments:

Search This Blog