Wednesday, November 13, 2019

Implement Generic Repository Pattern with Dependency Injection in Asp.net core with Code First Approach | Dependency Injection in ASP.NET Core

Hello & As-salam u alikum ! , In the last two articles we had discussed about basic Repository Pattern , There is the reference in the below link.

https://dotnetcorecommunity.blogspot.com/2019/11/repository-pattern-with-dependency.html

Now We Will discuss Generic Repository Pattern in asp.net core MVC, First Lets discuss what is Generic Repository Pattern.
You need to create separate repositories for each and every individual entity in your application while using basic or non-generic Repository, That was actually boring and repeating work, Particularly if all the repositories do the same kind of work. usually database CRUD operation & this is against of DRY principle because you repeat the same code again and again in each repository.



Step# 1:  
Create an asp.net core web project in visual studio 2017/ 2019 using .net core 2.2

Step# 
2:  

Add an Entity  "Employee" & "Department" using one to many relationship.




Step# 3:  

Install Entityframework Core using Nuget Packge Manager & Add a Db Connection class named as "AppdbContext" and add namespace .


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using GenericRepositoryPattern.Models;

namespace GenericRepositoryPattern.Models
{
    public class AppdbContext: DbContext
    {
   
        public AppdbContext(DbContextOptions<AppdbContext> options) : base(options)
        {

        }
        public DbSet<Employee> Employees { get; set; }

       public DbSet<.Department> Department { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
   
            base.OnModelCreating(modelBuilder);

        }


     
    }
}


Step# 4:  

Create an interface and declare all the method signature in interface. 


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

namespace GenericRepositoryPattern.Models
{
   public interface IGenericRepository<T> where T : class
    {
        IEnumerable<T> GetAll();
        T GetById(object id);
        void Insert(T obj);
        void Update(T obj);
        void Delete(object id);
        void Save();

    }
}




Step# 5:  

Create a generic repository class and paste the following code.


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

namespace GenericRepositoryPattern.Models
{
    public class GenericRepository<T> : IGenericRepository<T> where T : class

    {
        private AppdbContext _context = null;
        private DbSet<T> table = null;
     
        public GenericRepository(AppdbContext _context)
        {
            this._context = _context;
            table = _context.Set<T>();
        }
        public IEnumerable<T> GetAll()
        {
            return table.ToList();
        }
        public T GetById(object id)
        {
            return table.Find(id);
        }
        public void Insert(T obj)
        {
            table.Add(obj);
            Save();

        }
        public void Update(T obj)
        {
            table.Attach(obj);
            _context.Entry(obj).State = EntityState.Modified;
            Save();

        }
        public void Delete(object id)
        {
            T existing = table.Find(id);
            table.Remove(existing);
            Save();

        }
        public void Save()
        {
            _context.SaveChanges();
        }

    }
}



Step# 6:  
Go to the Home controller and paste the following code.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using GenericRepositoryPattern.Models;

namespace GenericRepositoryPattern.Controllers
{
    public class HomeController : Controller
    {
        private IGenericRepository<Employee> repository = null;
        private IGenericRepository<Department> repository2 = null;


        public HomeController(IGenericRepository<Employee> repository, IGenericRepository<Department> repository2)
        {
            this.repository = repository;
            this.repository2 = repository2;

        }
        [HttpGet]
        public ActionResult Index()
        {
            var model = repository.GetAll();
            return View(model);
        }


        public IActionResult Create()
        {
            ViewBag.DepartmentDepId = repository2.GetAll();
            return View();
        }
        [HttpPost]
        public IActionResult Create(Employee obj)
        {
            ViewBag.DepartmentDepId = repository2.GetAll();

            repository.Insert(obj);
            return RedirectToAction("Index");
        }


        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}


I only have added two actions in this example , View all and Add new records. You can do all the CRUD operation by doing the same.

Index.cshtml:  

@model IEnumerable<GenericRepositoryPattern.Models.Employee>

@{
    ViewData["Title"] = "Index";
}

<h1>Index</h1>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Address)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Email)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.photoPath)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Address)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Email)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.photoPath)
            </td>
            <td>
                <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
            </td>
        </tr>
}
    </tbody>
</table>


Create.cshtml:  

@model GenericRepositoryPattern.Models.Employee

@{
    ViewData["Title"] = "Create";
}

<h1>Create</h1>

<h4>Employee</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Address" class="control-label"></label>
                <input asp-for="Address" class="form-control" />
                <span asp-validation-for="Address" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Email" class="control-label"></label>
                <input asp-for="Email" class="form-control" />
                <span asp-validation-for="Email" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="photoPath" class="control-label"></label>
                <input asp-for="photoPath" class="form-control" />
                <span asp-validation-for="photoPath" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="DepartmentDepId" class="control-label"></label>
                <select asp-for="DepartmentDepId" class ="form-control" asp-items="@(new SelectList(@ViewBag.DepartmentDepId,"DepId", "Name"))"></select>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}



Step# 7:  
Place the connection string in the AppSetting.json file as i shown below .


Step# 8:  
open startup.cs file to configure middle-ware .




Step# 8:  
open the Package Manager Console, Run the Migration and Update-database command,

Commands:


  1. add-migration initial
  2. Update-database


Step#9:  
Run the application , you will get Index page of home which would be empty, Click on create button and add some data ,than it will be showing a list of data in table.


Conclusion :
that's all for this blog, we have successfully Implement the Generic Repository Pattern ,if you have more other entities in your database ,then you would not have to add new repository for that, as we have made a generic Repository for each and every entity.Thank you for watching.Have a great day .

Subscribe to my youtube : 

https://www.youtube.com/channel/UCHAmv9m1l_BqbiPFvwWv1aw 














0 Comments:

Post a Comment

Do not Add Spam links in the Comment Box

Subscribe to Post Comments [Atom]

<< Home