CRUD operations using Entity framework using Scaffolding ~ MiTechDev.com

Mitechdev.com is a programming blog which focused on Web Programming and development

Friday, 25 March 2016

CRUD operations using Entity framework using Scaffolding

23:34:00 Posted by raviteja swayampu , No comments

CRUD operations using Entity framework

Hello every one.it's time move some fast.Today we gonna do the basic CRUD operations using ASP.NET MVC with help of Entity framework and the power of Visual studio(Scaffolding).
If you are new to MVC please refer previous tutorials

Creting first ASP.NET MV
 applicationsIntroduction to ASP.NET MVC 
What is Model View Controller

Create a ASP.NET MVC web application using Visual studio..

CRUD operations using Entity framework in ASP.NET MVC
Create a Model class in Models folder by right click on models folder-->Add-->class and choose Class template from "Add new item".


Then replace the code using the following code below.Here in this model class i am created a some auto implemented classes that represents the columns present in the database table.Technically those are called as entities and classes are called as entity classes(Student.cs).

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

namespace CRUDoperations.Models
{
    public class Student
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public int phone { get; set; }
    }
}

Now create a database table in the sql server express by right click on App_Data folder(This folder generally contains the db files if you try to add sql express db outside of this folder visual studio won't allow it).rightclick on App_Start folder-->Add-->New Item-->choose Sql Database and name it as Database.mdf.

CRUD operations using ASP.NET MVC using entity framework

open server explorer -->create new table

CRUD operations using Entity freamework using scaffolding

CRUD operations in ASP.NET MVC using entity framework
click on update button in the image above and click on "update database" button which will be shown in next window(preview database updates window) to update the database with the table.
now your table created successfully.
Then build the solution once menu-->build-->build solution or use ctrl+shift+B.
now create a context class: this class acts as a interface between database and controller class.
before creating context class in your application first install Entity framework 5.0.0(don't install EF from nuget package manager because it install latest version of EF6.0 or above.The recent versions of entity framework won't support scaffolding mechanism) using below command in the package manager console.
Install-Package EntityFramework -Version 5.0.0
to install EF goto-->menu-->Tools-->Library package manager-->Package manager console-->paste command-->press enter..
Now replace the code present in the Student.cs with following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
//Entity namesapce must add to work with entity framework
using System.Data.Entity;   
//Models namespace helps context class to connect with model classes
using CRUDoperations.Models;
namespace CRUDoperations.Models
{
    public class Student
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public int phone { get; set; }
    }
}
//context class must be inherited from DbContext class
//which is present Entity namespace..
public class Context : DbContext
{
    //Context class stores the data which comes from db in Dbset class
    public DbSet<Student> Students { get; set; }
}

Now scaffolding comes  into picture here.(build solution once.)
Create a controller.right click controller-->Add-->Controller-
CRUD operations in ASP.NET MVC using entityframework
and select Model and context in next window

CRUD operations using Entity framework using Scaffolding
and click on add then visual studio automatically generates the controller actions methods for CRUD operations and corresponding views in the Views folder.
you can see the generated files in the solutions explorer.
CRUD operations using Entity framework using Scaffolding

below is code generated in controller class

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using CRUDoperations.Models;

namespace CRUDoperations.Controllers
{
    public class HomeController : Controller
    {
        private Context db = new Context();

        // GET: /Home/
        public ActionResult Index()
        {
            return View(db.Students.ToList());
        }

        // GET: /Home/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }

        // GET: /Home/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: /Home/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include="ID,Name,Address,phone")] Student student)
        {
            if (ModelState.IsValid)
            {
                db.Students.Add(student);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(student);
        }

        // GET: /Home/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }

        // POST: /Home/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include="ID,Name,Address,phone")] Student student)
        {
            if (ModelState.IsValid)
            {
                db.Entry(student).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(student);
        }

        // GET: /Home/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }

        // POST: /Home/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Student student = db.Students.Find(id);
            db.Students.Remove(student);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

the output will be like this in the browser


I hope you understand If any queries please comment me when i am free i will answer you...

0 comments:

Post a Comment