ASP.Net Core MVC Project Part 5

In this article we will create repository classes by implementing interfaces IProductRepository and ICategoryRepository so before reading this article please read ASP.Net Core MVC Project Part 3 and ASP.Net Core MVC Project Part 4 . This article is fifth part of Asp.Net Core MVC project series.

Below are the IProductRepository and ICategoryRepository interfaces:

namespace eShop.Repositories
{
    public interface IProductRepository
    {
        IEnumerable<Product> GetAllProduct { get; }
        IEnumerable<Product> GetProductOnSale { get; }
        Product GetProductById(int ProudctId);
    }
}
namespace eShop.Repositories
{
   public interface ICategoryRepository
    {
        IEnumerable<Category> GetAllCategories { get; }
    }
}

Below is the AppDbContext class which we are using for Database connectivity:

public class AppDbContext:DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options):base(options)
    {

    }
    public DbSet<Product> Products { get; set; }
    public DbSet<Category> Categories { get; set; }

}

Now we will implement these interfaces and create repository classes.

Repository Pattern Implementation

Right click on Repositories folder in the project and add 2 class files ProductRepository.cs and CategoryRepository.cs. Now implement interfaces IProductRepository and ICategoryRepository. Below is the implementation of ICategoryRepository in CategoryRepository.cs file :

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

namespace eShop.Repositories
{
    public class CategoryRepository : ICategoryRepository
    {
    private AppDbContext _appDbContext;
    public CategoryRepository(AppDbContext appDbContext)
    {
        _appDbContext = appDbContext;
    }
    public IEnumerable<Category> GetAllCategories => _appDbContext.Categories;
    }
}

In class CategoryRepository, there is a read only field _appDbContext of type AppDbContext and we are injecting its value through constructor , it means object of AppDbContext will be provided by run time when object of CategoryRepository is created. Finally we have implemented GetAllCategories property.

Below is the implementation of IProductRepository in ProductRepository .cs file:

namespace eShop.Repositories
{
public class ProductRepository : IProductRepository
{
private readonly AppDbContext _appDbContext;
public ProductRepository(AppDbContext appDbContext)
{
    _appDbContext = appDbContext;
}
public IEnumerable<Product> GetAllProduct
{
    get
    {
        return _appDbContext.Products.Include(c => c.Category);
            
    }
}
public IEnumerable<Product> GetProductOnSale
{
    get
    {
        return _appDbContext.Products.Include(c => c.Category).Where(p=>p.IsOnSale);

    }
}
public Product GetProductById(int ProudctId)
{
    return _appDbContext.Products.FirstOrDefault(p=>p.ProductId== ProudctId);
}
}
}

In above code, we have declared field of type AppDbContext and we are injecting its value through constructor.

Please see below code, we are including Category object with each Product object.

public IEnumerable<Product> GetAllProduct
{
    get
    {
        return _appDbContext.Products.Include(c => c.Category);
            
    }
}

Method GetProductOnSale() returns Product object which is available for Sale.

Now we need to add ProductRepository and CategoryRepository as services in ConfigureServices() method of Startup class so that object of these can be created by run time.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using eShop.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using eShop.Repositories;
namespace eShop
{
public class Startup
{
public IConfiguration Configuration { get;}
public Startup(IConfiguration configurationParam)
{
    Configuration = configurationParam;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options=>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddControllersWithViews();
services.AddScoped<ICategoryRepository, CategoryRepository>();
services.AddScoped<IProductRepository, ProductRepository>();
}
                
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
    name:"default",
    pattern:"{controller=Home}/{action=Index}/{id?}"
    );
});
}
}
}

In this article we have seen repository pattern implementation.

Download code from below URL:
https://github.com/vijendra-ksh/eShop

Below are list of previous articles in this project series :

a) ASP.Net Core MVC Project Part 1
b) ASP.Net Core MVC Project Part 2
c) ASP.Net Core MVC Project Part 3

d) ASP.Net Core MVC Project Part 4

Please like our Facebook page for getting updates about new articles :
https://www.facebook.com/logixn

Leave a Comment

Your email address will not be published. Required fields are marked *