Saturday, July 12, 2014

CRUD Operation Using Entity Framework in ASP.Net MVC 4

CRUD Operation Using Entity Framework in ASP.Net MVC 4

In this blog, I am going to tell how to perform create, read, update and delete operations using entity framework in asp.net mvc 4.

Step -1

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












And enter some dummy data in the table.

Now create an asp.net mvc 4 web application and install the entity framework in your project like this:















































Step -2

Now add a model class named “StudentInformation” to the project 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 CRUDWithEntityFramework.Models
{
    [Table("StudentInformation")]  // Table Name
    public class StudentInformation
    {
        [Key] //Primary Key
        public int StudentId { get; set; }

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

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

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

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

Step-3

Next we need to create a DBContext object named “StudentDBContext” that will be responsible for performing all the CRUD operations on “StudentInformation” model class.

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

namespace CRUDWithEntityFramework.Models
{
    public class StudentDBContext : DbContext
    {
        public DbSet<StudentInformation> student { get; set; }
    }
}

Step -4

Create a connection string in the web.config like this:
<connectionStrings>
    <add name="StudentDBContext" connectionString="Data Source=DELL-PC; Initial Catalog=StudentDB; Integrated Security = true;" providerName="System.Data.SqlClient"/>
  </connectionStrings>

The important thing to notice here is that the name of the connectionString is same as the DbContext class that we have created. If we keep the name of the connectionString same as the DbContext class the corresponding DbContext class will use the connectionString to persist the data, but this is also flexible so that we have the possiblity of giving custom names to the connectionStrings.

Step -5

Now create a controller class named “StudentController” and it will perform the CRUD operations on the “StudentInformation” entity and write the below in it:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CRUDWithEntityFramework.Models;

namespace CRUDWithEntityFramework.Controllers
{
    public class StudentController : Controller
    {
        StudentDBContext context = new StudentDBContext();

        public ActionResult Index()
        {
            List<StudentInformation> studentList = context.student.ToList();
            return View(studentList);
        }

        public ActionResult Details(int id)
        {
            StudentInformation student = context.student.SingleOrDefault(m => m.StudentId == id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }

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

        [HttpPost]
        public ActionResult Create(StudentInformation student)
        {
            if (ModelState.IsValid)
            {
                context.student.Add(student);
                context.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(student);
        }

        public ActionResult Edit(int id)
        {
            StudentInformation student = context.student.Single(m => m.StudentId == id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }

        [HttpPost]
        public ActionResult Edit(int id, StudentInformation student)
        {
            StudentInformation _student = context.student.Single(m=>m.StudentId == id);
            if (ModelState.IsValid)
            {
                _student.Name = student.Name;
                _student.Age = student.Age;
                _student.Address = student.Address;
                _student.Course = student.Course;

                context.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(student);
         }

        public ActionResult Delete(int id)
        {
            StudentInformation student = context.student.Single(m=>m.StudentId == id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }

        [HttpPost]
        public ActionResult Delete(int id, StudentInformation student)
        {
            StudentInformation _student = context.student.Single(m=>m.StudentId == id);
            context.student.Remove(_student);
            context.SaveChanges();
            return RedirectToAction("Index");
        }

    }
}

Step -6

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.

Step-7

Now open the “RouteConfig.cs” file in the App_Start folder and change the name of the controller from home to Student like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace CRUDWithEntityFramework
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Student", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

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