MVC CRUD operations using Entity Framework


This article is all about ASP.NET MVC CRUD operations using Entity Framework 

Here we will learn how to implement crud operations in asp.net mvc using Entity Framework 


Step 1 Create a Table EMP


Step 2 Create a Asp.net MVC Application Step by Step









Step 3 Add Entity Framework in Model folder

    1


    2


    3


    4


   5


    6


    7


   8



Step 4 Create HomeController class in Controller folder and give name 
            is HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC_Crud_OperationEntityFramework.Models;

namespace MVC_Crud_OperationEntityFramework.Controllers
{
    public class HomeController : Controller
    {
        MySampleDBEntities db = new MySampleDBEntities();
        public ActionResult Index()
        {
            List<Emp> Emplist = db.Emps.ToList();
            return View(Emplist);
        }

        public ActionResult Details(int id)
        {
            Emp obj = db.Emps.Find(id);            
            return View(obj);
        }
        
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create( Emp obj)
        {
            db.Emps.Add(obj);
            db.SaveChanges();

            return RedirectToAction("index");
        }
        [HttpGet]
        public ActionResult Edit(int id)
        {
            Emp obj = db.Emps.Find(id);
            return View(obj);
        }

        [HttpPost]
        public ActionResult Edit(Emp obj)
        {
            db.Entry(obj).State = System.Data.Entity.EntityState.Modified;

            db.SaveChanges();
            return RedirectToAction("index");
        }

        public ActionResult Delete(int id)
        {
            Emp obj =db.Emps.Find(id);
            return View(obj);
        }

        [HttpPost]
        [ActionName("Delete")]
        public ActionResult DeleteConfirm (int id)
        {
            Emp obj = db.Emps.Find(id);
            db.Emps.Remove(obj);
            db.SaveChanges();
            return RedirectToAction("index");
        }
    }
}



Step 5 Add view using Scaffolding.............






Share this

Previous
Next Post »

1 comments:

comments
October 4, 2021 at 1:24 AM delete


This is really an awesome article. Thank you for sharing this.It is worth reading for everyone.
Yii Framework Development Company in India

Reply
avatar