---
title: "Curd Operation using stored procedure through entity framework"  
description: "In this article I will explain that how to do create, edit, Update, select and delete operation with stored procedure entity framework means data firs"  
author: "Manish Kumar"  
published: 2017-02-03  
updated: 2018-03-17  
canonical: https://www.mindstick.com/blog/11289/curd-operation-using-stored-procedure-through-entity-framework  
category: "c#"  
tags: ["mvc4"]  
reading_time: 5 minutes  

---

# Curd Operation using stored procedure through entity framework

In this article I will explain that how to do **create, edit, Update, select and delete** operation with [stored procedure](https://www.mindstick.com/articles/803/using-stored-procedure-in-asp-dot-net) [entity framework](https://www.mindstick.com/articles/1566/crud-operations-using-entity-framework-code-first-approach) means [data first approach](https://www.mindstick.com/forum/34493/call-stored-procedures-with-entity-framework-6-data-first-approach-in-asp-dot-net-mvc-4).

**First step is to create data base and table.**

```
CREATE TABLE [dbo].[RegistrationForm](          [Id] [int] IDENTITY(1,1) primary key NOT NULL,          [FName] [varchar](50) NULL,          [MName] [varchar](50) NULL,          [LName] [varchar](50) NULL,          [Dob] [datetime] NOT NULL,          [Mobile] [nchar](10) NULL,          [City] [varchar](50) NULL,          [Pin] [varchar](50) NULL,          [Address] [varchar](250) NULL,);
```

## \

**And for [bind dropdown](https://www.mindstick.com/forum/33512/how-to-bind-dropdown-list-using-knockout-js-in-mvc-entity-framework) with database [create table](https://www.mindstick.com/articles/443/how-to-create-table-in-sql-server) and store records**

```
CREATE TABLE [dbo].[CountryList](          [Id] [int] IDENTITY(1,1) primary key NOT NULL,          [Country] [varchar](50) NULL,);
```

**Now will create stored [procedure for Insert](https://www.mindstick.com/forum/59/how-we-make-the-procedure-for-insert-in-sql-server), select and delete record**

**Procedure for insert record**

```
Create Proc [dbo].[InsertRecord](@Fname varchar(50),@MName varchar(50 ),@LName varchar(50),@Dob datetime,@Mobile nchar(10),@City varchar(50),@Pin varchar(50),@Address
varchar(250))AsBeginInsert into
RegistrationForm(FName,MName,LName,Dob,Mobile,City,Pin,Address) values(@Fname,@MName,@LName,@Dob,@Mobile,@City,@Pin,@Address)End
```

## Procedure for delete record

```
Create Proc [dbo].[deleterecord](@id int)asBeginDelete from dbo.RegistrationForm where
Id=@idEnd
```

## for selecting record

```
Create Proc [dbo].[GetbyId](@Id int)AsBeginSelect * from RegistrationForm where
Id=@IdEnd
```

## And for Updating records

```
Create proc [dbo].[UpdateRecord](  @id int, @FirstName varchar(50), @MName varchar(50), @LName varchar(50), @Dob datetime, @Mobile nchar(10), @City varchar(50), @Pin varchar(50), @Address varchar(250) )asbegin UPDATE dbo.RegistrationFormSETFName=@FirstName,MName=@MName,LName=@LName,Dob=@Dob,Mobile=@Mobile,City=@City,Pin=@Pin,Address=@Addresswhere Id=@Idend
```

## Now add New Project Demo. Right Click on the Models folder and select

## \

**Ado.Net [Entity Data Model](https://www.mindstick.com/articles/594/ado-dot-net-entity-data-model-in-wpf)**

![Curd Operation using stored procedure through entity framework](https://www.mindstick.com/blogs/7f1289d4-9008-4a01-9269-2955cdcecda7/images/06d54593-036e-49c3-8a4f-d6d5588f0ae4.png)\

**And click generate From Database**

![Curd Operation using stored procedure through entity framework](https://www.mindstick.com/blogs/7f1289d4-9008-4a01-9269-2955cdcecda7/images/4bec30ee-7788-4fed-8c96-ab048eb7b29d.png)\

**And next and then give connection information and select your database.**

![Curd Operation using stored procedure through entity framework](https://www.mindstick.com/blogs/7f1289d4-9008-4a01-9269-2955cdcecda7/images/fc3e94f9-6bd9-4e86-9928-d948323e789d.png)

**Then choose tables and store procedure.**

![Curd Operation using stored procedure through entity framework](https://www.mindstick.com/blogs/7f1289d4-9008-4a01-9269-2955cdcecda7/images/dcd8f65a-b7f4-4786-8f2f-c9445082ec54.png)

**And then finish.**

In the next step we will create Home Controller for adding controller right click on the controllers folder and go to add and then click controller then a [pop up](https://www.mindstick.com/forum/346/how-to-show-a-pop-up-messagebox) will be appear from here you can change you can give your controller name .

![Curd Operation using stored procedure through entity framework](https://www.mindstick.com/blogs/7f1289d4-9008-4a01-9269-2955cdcecda7/images/2e7bb5ee-ffa5-4491-8385-1212eae9d3c5.png)\

**After adding controller your home controller will look like this.**

```
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc; namespace
MvcApplication3.Controllers{    public class HomeController : Controller    {        //        // GET: /Home/         public ActionResult Index()        {            return View();        }     }}
```

For adding view right click on the Index method and add view.

In the Index view we can design our presentation view.

```
@model DemoStoreproc.Models.RegistrationForm   
@{    ViewBag.Title = "Index";}<style>    Input[type="Text"] {        width:200px;            }    Input[type="Submit"] {        color:blue;        background-color:aquamarine;        width:90px;            }</style>      <script src="~/Scripts/jquery.validate.min.js"></script>    <script src="~/Scripts/jquery.validate.unobtrusive.js"></script><script src="~/Scripts/jquery-3.1.1.js"></script>@*<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>*@    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>      <h2>Registration Form</h2> @using (Ajax.BeginForm("Add", "Home", new AjaxOptions    {        HttpMethod = "POST",        UpdateTargetId = "target",        OnSuccess = "updateSuccess",     }, new { id = "form1" })){<table>    <tr>        <td>First Name</td>        <td>@Html.TextBoxFor(model => model.FName)</td>        <td>Middle Name</td>        <td>@Html.TextBoxFor(model => model.MName)</td>        <td>Last Name</td>        <td>@Html.TextBoxFor(model => model.LName)</td>    </tr>    <tr>        <td>Dob</td>        <td>@Html.TextBoxFor(model => model.Dob)</td>        <td>Mobile</td>        <td>@Html.TextBoxFor(model => model.Mobile)</td>        <td>Country</td>        <td>@Html.DropDownListFor(model =>model.City,new SelectList(ViewBag.city,"Country","Country"))</td>    </tr>    <tr>        <td>Pin</td>        <td>@Html.TextBoxFor(model => model.Pin)</td>        <td>Address</td>        <td>@Html.TextAreaFor(model =>model.Address)</td>     </tr>    <tr><td><input type="submit" value="Save" /></td>       @ViewData["Message"]     </tr></table>}<div id="target">    @Html.Partial("List");</div>  <script>            function updateSuccess(data) {             $('form')[0].reset();                     }</script>
```

And for adding partial view right click on the views folder then go to add and then click view. And tick at the Create as a partial view.

![Curd Operation using stored procedure through entity framework](https://www.mindstick.com/blogs/7f1289d4-9008-4a01-9269-2955cdcecda7/images/f2107221-fef3-4bdc-ba96-d6760de176c7.png)

**In the [partial view](https://www.mindstick.com/articles/1132/auto-refresh-partial-view-in-asp-dot-net-mvc) we create grid for show records. And for filling records I have used view bag.**

```
<table border="1" cellspacing="0" cellpadding="0">    <tr>        <td>First Name</td>        <td>Middle Name</td>        <td>Last Name</td>        <td>DOB</td>        <td>Mobile</td>        <td>City</td>        <td>Pin</td>        <td>Address</td>    </tr>    @foreach (var d in ViewBag.users as List<DemoStoreproc.Models.RegistrationForm>)    {        <tr>            <td>@d.FName</td>            <td>@d.MName</td>            <td>@d.LName</td>            <td>@(d.Dob != null ? d.Dob.ToString("dd/MM/yyyy") : "")</td>            <td>@d.Mobile</td>            <td>@d.City</td>            <td>@d.Pin</td>            <td>@d.Address</td>            <td>@Html.ActionLink("Edit", "Edit", new { Id = d.Id },                 new AjaxOptions                 {                     OnSuccess="Filldata",                     InsertionMode = InsertionMode.Replace,                     HttpMethod = "GET",                  }) </td>            <td>@Ajax.ActionLink("Delete", "Delete", new { Id = d.Id },                 new AjaxOptions                 {                    UpdateTargetId="target",                     InsertionMode = InsertionMode.Replace,                     HttpMethod = "POST"                 })</td>          </tr>    }</table><script>    function Filldata(data) {        console.log(data);        $('#Id').val(data.Id);        $('#FName').val(data.FName);       $('#MName').val(data.MName);        $('#LName').val(data.LName);                $('#Dob').val(data.Dob);               $('#Mobile').val(data.Mobile);        $('#Pin').val(data.Pin);        $('#Address').val(data.Address);    }</script>
```

\

**For binding dropdown in view using viewbag. In the controller**

```
        public ActionResult Index()        {            var context = new DemoEntities();            ViewBag.Country =context.CountryLists;            return View();        }
```

**And in the view**

```
<td>@Html.DropDownListFor(model => model.City, new SelectList(ViewBag.Country, "Country", "Country"), "-Select-")</td>
```

In the home controller write the following code for Inserting records, editing records and deleting records **DemoEntities** is the [database context](https://www.mindstick.com/forum/158712/what-is-the-role-of-a-database-context-in-entity-framework) name. We can access stored procedure using instance of database context. InsertRecord is the stored procedure name.

```
using (var context = new DemoEntities())            {                               context.InsertRecord(Model.FName,Model.MName, Model.LName, Model.Dob, Model.Mobile, Model.City, Model.Pin,
                  Model.Address);                context.SaveChanges();}       
```

**All controller code is**

```
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;usingDemoStoreproc.Models;using System.Data;using System.Data.Entity; namespace
DemoStoreproc.Controllers{    public class HomeController : Controller    {        //        // GET: /Home/         public ActionResult Index()        {            var context = new DemoEntities();            ViewBag.Country =context.CountryLists;            ViewBag.users =context.RegistrationForms.ToList();             return View();        }         [HttpPost]        public ActionResult Add(RegistrationForm Model)        {            using (var context = new DemoEntities())            {                if (Model.Id == 0)                {                   
context.InsertRecord(Model.FName, Model.MName, Model.LName, Model.Dob,
Model.Mobile, Model.City, Model.Pin, Model.Address);                 }                else                {                   
context.UpdateRecord(Model.Id, Model.FName, Model.MName, Model.LName,
Model.Dob, Model.Mobile, Model.City, Model.Pin, Model.Address);                }                 //context.RegistrationForms.Add(Model);                ViewData["Message"] = "Success";             }            var context1 = new DemoEntities();            ViewBag.users =context1.RegistrationForms.ToList();            return PartialView("List");        }                public ActionResult Edit(int id)        {            var context = new DemoEntities();            //var data = context.GetbyId(id);           var data =context.RegistrationForms.Find(id);            //return PartialView("List",data);            return Json(data, JsonRequestBehavior.AllowGet);        }         public ActionResult Delete(int id)        {            var context = new DemoEntities();            context.deleterecord(id);            ViewBag.users =context.RegistrationForms.ToList();            return PartialView("List");         }    }}
```

**Our page will look like**

![Curd Operation using stored procedure through entity framework](https://www.mindstick.com/blogs/7f1289d4-9008-4a01-9269-2955cdcecda7/images/bbbdde92-9d40-4687-981a-9ffda1dac330.png)\

---

Original Source: https://www.mindstick.com/blog/11289/curd-operation-using-stored-procedure-through-entity-framework

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
