Saturday, July 12, 2014

CRUD Operation Using Repository Pattern with Entity Framework in Asp.Net MVC 4

CRUD Operation Using Repository Pattern with Entity Framework in Asp.Net MVC 4

In this blog, I am going to tell how to preform create, read, update/edit and delete using repository pattern with entity framework in asp.net mvc 4.

If you want to learn about entity framework first, then you can read my blog here:



The Repository pattern is used to create an abstraction layer between the data access layer and the business logic layer of an application. It is a data access pattern that prompts a more loosely coupled approach to data access.

Step-1

First create a table named ”StudentInformation” in the database like this:


And enter some dummy data in the table.

Step-2

Now create an empty asp.net mvc 4 web application with razor view engine and install the entity framework using nugget package and add a model class named “StudentInformation” and write the below code in it:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace CRUDWithRepositoryPattern.Models
{
    [Table("StudentInformation")] // table name
    public class StudentInformation
    {
        [Key] //Primary Key
        public int StudentId { get; set; }

        [Required(ErrorMessage="Name is mandatory")]
        [Display(Name="NAME")]
        [MaxLength(50)]
        public string Name { get; set; }

        [Required(ErrorMessage="Age is mandatory")]
        [Display(Name="AGE")]
        [MaxLength(50)]
        public string Age { get; set; }

        [Required(ErrorMessage="Address is mandatory")]
        [Display(Name="ADDRESS")]
        [MaxLength(50)]
        public string Address { get; set; }

        [Required(ErrorMessage="Course is mandatory")]
        [Display(Name="COURSE")]
        [MaxLength(50)]
        public string Course { get; set; }
    }
}

Step-3

Add a DbContext class to the project like this:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace CRUDWithRepositoryPattern.Models
{
    public class StudentDbContext : DbContext
    {
        public StudentDbContext()
            : base("name=StudentConnectionString") // Custom Connection String Name
        {
        }

        public DbSet<StudentInformation> Student { get; set; }
    }
}

Step-4

Now add the connection string in the web.config file like this:

<connectionStrings>
  <add name="StudentConnectionString" connectionString="Data Source=DELL-PC;Initial Catalog=StudentDB;Integrated Security=true;" providerName="System.Data.SqlClient"/>
</connectionStrings>


Step-5

Now add a folder to the project named “Repository” and an interface to this folder named “IStudentRepository”, this interface we derive from IDisposable type of interface and write the below in it:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CRUDWithRepositoryPattern.Models;

namespace CRUDWithRepositoryPattern.Repository
{
    interface IStudentRepository : IDisposable
    {
        IEnumerable<StudentInformation> GetStudent();
        StudentInformation GetStudentById(int StudentId);
        void CreateNew(StudentInformation student);
        void EditStudent(StudentInformation student);
        void DeleteStudent(int StudentId);
        void Save();
    }
}


Step-6

Now add a class named “StudentRepository” to the Repository folder and implement all the methods of IStudentRepository interface, but with the help of Entity Framework. Now here comes the use of our StudentDbContext class, we already have this class in our existing solution, so we don’t have to touch this class, simply, write our business logic in the interface methods implemented in StudentRepository class, like this:

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

namespace CRUDWithRepositoryPattern.Repository
{
    public class StudentRepository : IStudentRepository
    {
        private StudentDbContext _context;

        public StudentRepository(StudentDbContext studentContext)
        {
            this._context = studentContext;
        }

        public IEnumerable<StudentInformation> GetStudent()
        {
            return _context.Student.ToList();
        }

        public StudentInformation GetStudentById(int StudentId)
        {
            return _context.Student.Find(StudentId);
        }

        public void CreateNew(StudentInformation student)
        {
            _context.Student.Add(student);
        }

        public void EditStudent(StudentInformation student)
        {
            _context.Entry(student).State = System.Data.Entity.EntityState.Modified;
        }

        public void DeleteStudent(int StudentId)
        {
            StudentInformation student = _context.Student.Find(StudentId);
            _context.Student.Remove(student);
        }

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

        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    _context.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}


Step -7

Now add a controller to the project named “HomeController” and add the create an instance of the IStudentRepository interface in the Home Controller and initialize the student repository in the constructor of Home Controller as in the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CRUDWithRepositoryPattern.Models;
using CRUDWithRepositoryPattern.Repository;

namespace CRUDWithRepositoryPattern.Controllers
{
    public class HomeController : Controller
    {
        private IStudentRepository _StudentRepository;

        public HomeController()
        {
            this._StudentRepository = new StudentRepository(new StudentDbContext());
        }

        public ActionResult Index()
        {
            var students = from student in _StudentRepository.GetStudent() select student;
            return View(students);
        }

        public ViewResult Details(int Id)
        {
            StudentInformation student = _StudentRepository.GetStudentById(Id);
            return View(student);
        }

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

        [HttpPost, ActionName("Create")]
        public ActionResult CreateNewConfirmed(StudentInformation student)
        {
            if (ModelState.IsValid)
            {
                _StudentRepository.CreateNew(student);
                _StudentRepository.Save();
                return RedirectToAction("Index");
            }

            return View(student);
        }

        public ActionResult Edit(int Id)
        {
            StudentInformation student = _StudentRepository.GetStudentById(Id);
            return View(student);
        }

        [HttpPost, ActionName("Edit")]
        public ActionResult EditConfirmed(StudentInformation student)
        {
            if (ModelState.IsValid)
            {
                _StudentRepository.EditStudent(student);
                _StudentRepository.Save();
                return RedirectToAction("Index");
            }
            return View(student);
        }

        public ActionResult Delete(int Id)
        {
            StudentInformation student = _StudentRepository.GetStudentById(Id);
            return View(student);
        }

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int Id)
        {
            StudentInformation student = _StudentRepository.GetStudentById(Id);
            _StudentRepository.DeleteStudent(Id);
            _StudentRepository.Save();
            return RedirectToAction("Index");
        }

    }
}


Step -8

Now add the view for list, details, create, edit and delete to the project – these views will be strongly typed and scaffold views.

Index View – To show the list of students


Create View – To add a new student.


Details View – To show the details of a particular student.


Edit View – To edit/update the details of a particular student.


Delete View – To delete a particular student.



As you can see that using the Scaffold template option – the view is created for you and don’t have to write anything in the view by itself.

After doing all the above things your solution explorer will look like this:



Output

Now build the application and run it:

First you will see that a list of students:


Now click Create new


Now click on Edit



Now click on Details


Now click on Delete



Thank you for reading this article, please put your valuable comment or any suggestion/question in the comment box. 



No comments:

Post a Comment