Repository Method in Asp.Net MVC

In previous session we learn to how to use Repository pattern for an insert, update  delete and getall or getbyid  by Creating a  Service.

Now ,we will utilize the service in Controller for different Action.

1> we will call the service and initiate through constructor  .


          private readonly IRepository<Types, int> _typesRepository;
          private readonly TypeService _typesServices;

          

          public TypesController(IRepository<Types, int> typesRepository,
          DefaultConnection  dbContext, TypeService typeServices)// contructor...
         {
            this._typesRepository = typesRepository;
            this._dbContext = dbContext;
            this._typesServices = typeServices;
         }    
       
2> Service have different functionality according to Actions.  Take a look.


Action                                        Service
Index                                       _typesServices.GetAll() // View the all data.
Create                                      _typesServices.Insert(model); // insert the data
Edit                                          _typesServices.GetById(id)  // To find the single row
                                                _typesServices.Update(type); // update the data
Delete                                      _typesServices.Delete(type) // Delete the data


3> Here the Code we used Repository method in Bold font.

 Here I am not using the parameter constructor.

using ItsMe.Areas.Admin.Models;
using ItsMe.Models;
using ItsMe.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ItsMe.Areas.Admin.Controllers
{
    [Authorize]
    public class TypesController : Controller
    {
        TypeService _typesServices = new TypeService();   

        public ActionResult Index()
        {
            return View(_typesServices.GetAll());
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(Types model)
        {
            _typesServices.Insert(model);
            return RedirectToAction("Index");
        }

        public ActionResult Edit(int id)
        {
            return View(_typesServices.GetById(id));
        }

        [HttpPost]
        public ActionResult Edit(Types model)
        {
            var type = _typesServices.GetById(model.Id);
            type.Name = model.Name;
            type.Status = model.Status;
            _typesServices.Update(type);
            return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult Delete(int id)
        {
            var type = _typesServices.GetById(id);
            _typesServices.Delete(type);
            return RedirectToAction("Index");
        }
     }
}

4> Insert , update and List in UI






Share this

Previous
Next Post »