How to Add Update Delete using entity framework

Total Post:27

Points:189
 1484  View(s)
Ratings:
Rate this:
Hi Buddy

Please help me  How to Add Update Delete using entity framework .

Thanks


  1. Post:52

    Points:366
    Re: How to Add Update Delete using entity framework

     I am providing you the solution of your question. Using entity framework and repository pattern

    First create a demo database and create table RegistrationForm

    CREATE TABLE [dbo].[RegistrationForm](
              [Id] [int] IDENTITY(1,1) 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 CountryList table and Insert record


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

     

     

     

    Then create a new project and right click on model folder and select ado.net entity data model 




    And then And next and give sever and user name and password and select your database .Then your entity framework will be generated. It will look like this 

    For data annotation we  have to add another class in model we cannot add data annotation in generated models class because when we update our entity framework our important  validation will be loss to recover from this problem we will create meta class in the models folder.

    And add following code

     

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
     
    namespace TestSol.Models
    {
        public class RegistrationFormMeta
        {
            public int Id { get; set; }
     
            [Required(ErrorMessage="First Name is require!!")]
            public string FName { get; set; }
     
            public string MName { get; set; }
            public string LName { get; set; }
            public DateTime Dob { get; set; }
            public string Mobile { get; set; }
            public string City { get; set; }
              
           [Required(ErrorMessage="pin is require!!")]
           [RegularExpression("^[0-9]{6}$" , ErrorMessage = "Pin must be Numeric and <=6")]
            public string Pin { get; set; }
     
            public string Address { get; set; }
        }
        public class CountryListMeta
        {
            public int Id { get; set; }
            public string Country { get; set; }
        }
    }

      

    Meta classes contain all the validation attribute to associate this class to metadata add a class in the models folder and name it Partial

     

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.ComponentModel.DataAnnotations;
     
    namespace TestSol.Models
    {
        [MetadataType(typeof(RegistrationFormMeta))]
        public partial class RegistrationForm
        {
        }
        [MetadataType(typeof(CountryListMeta))]
        public partial class CountryList
        {
        }
    }

     

     Now I will use repository design pattern for all the curd operation. In repository we move all data access code into one place. Now I will create IRepository class in the models folder 

     

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using TestSol.Models;
     
    namespace TestSol.Models
    {
        public interface IRepository<T> where T:class
        {
            IEnumerable<T> SelectAll();
            T SelectByID(object id);
            void Insert(T obj);
            void Update(T obj);
            void Delete(object Id);
        }
    }

      

    This is an interface so for implementation we will create a class in the models folder and will implement this interface into that 

     

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using TestSol.Models;
    using System.Data.Entity;
    using System.Data;
     
     
    namespace TestSol.Models
    {
        public class Repository<T>:IRepository<T> where T:class
        {
            private DemoEntities db = null;
            private DbSet<T> table = null;
             public Repository()
            {
                this.db = new DemoEntities();
                table = db.Set<T>();
            }
     
             public Repository(DemoEntities db)
            {
                this.db = db;
                table = db.Set<T>();
            }
     
            public IEnumerable<T> SelectAll()
            {
                return table.ToList();
            }
     
            public T SelectByID(object id)
            {
                return table.Find(id);
            }
     
            public void Insert(T obj)
            {
                table.Add(obj);
                db.SaveChanges();
            }
     
            public void Update(T obj)
            {
                table.Attach(obj);
                db.Entry(obj).State = EntityState.Modified;
                db.SaveChanges();
            }
     
            public void Delete(object Id)
            {
                T existing = table.Find(Id);
                table.Remove(existing);
                db.SaveChanges();
               
            }
     
        }
    }
     

     Add a new class in the models folder for setting the property for repository  

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
     
    namespace TestSol.Models
    {
        public class DML
        {
            public IRepository<RegistrationForm> RegistrationForm
            {
                get
                {
                    return new Repository<RegistrationForm>();
                }
            }
            public IRepository<CountryList> CountryList
            {
                get
                {
                    return new Repository<CountryList>();
                }
            }
        }
    }
     

     

    Now we will create unit of work for working with all the model classes. 

    using TestSol.Models;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
     
    namespace TestSol.Controllers
    {
        public class BaseController : Controller
        {
            //
            // GET: /Base/
     
            protected DML Uow { get; set; }
            private DemoEntities db = null;
            public BaseController()
            {
     
                Uow = new DML();
            }
     
        }
    }
     

     

    Now add a home controller and inherit base controller in it. In the home controller I have create add, edit, delete and Update action 

     

     

    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using TestSol.Models;
     
    namespace TestSol.Controllers
    {
        public class HomeController : BaseController
        {
            //
            // GET: /Home/
     
            public ActionResult index()
            {
     
                ViewBag.Users = Uow.RegistrationForm.SelectAll();
                return View();
            }
            public ActionResult Add()
            {
                ViewBag.Country = Uow.CountryList.SelectAll();
                return PartialView();
            }
     
            [AcceptVerbs(HttpVerbs.Post)]
            public ActionResult Add(RegistrationForm model)
            {        
                if (ModelState.IsValid)
                {
                    if (model.Id ==0)
                    {
                        Uow.RegistrationForm.Insert(model);
     
                    }
                    else
                    {
                        var data = Uow.RegistrationForm.SelectByID(model.Id);
                        if (data == null)
                            Uow.RegistrationForm.Insert(model);
                        else
                            Uow.RegistrationForm.Update(model);
                    }
                }
                ViewBag.Users = Uow.RegistrationForm.SelectAll();
                return PartialView("List");
     
            }
     
            public ActionResult Edit(int id)
            {
                ViewBag.Country = Uow.CountryList.SelectAll();
                return PartialView("Add", Uow.RegistrationForm.SelectByID(id));
            }
            [HttpPost]
            public ActionResult Delete(int id)
            {
                Uow.RegistrationForm.Delete(id);
                ViewBag.users = Uow.RegistrationForm.SelectAll();
                return PartialView("List");         
     
            }
     
            public ActionResult GetUser(string d)
            {
                if (!string.IsNullOrEmpty(d.Trim()))
                    ViewBag.Users = Uow.RegistrationForm.SelectAll().Where(x => d.Contains(x.FName) || d.Contains(x.LName) || d.Contains(x.Dob.ToString()) || d.Contains(x.City)).ToList();
                else
                    ViewBag.Users = Uow.RegistrationForm.SelectAll().ToList();
                   return PartialView("List");
            }
            public ActionResult GetRecord()
            {
                ViewBag.Users = Uow.RegistrationForm.SelectAll();
                return PartialView("UserList");
            }
     
     
     
        }
    }
     


    Our index view code in this I have added bootstrap library for better look and ajax validation 

    @model TestSol.Models.RegistrationForm
    @{
        Layout = null;
    }
     
    <!DOCTYPE html>
     
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <link href="~/Content/bootstrap.css" rel="stylesheet" />
        <link href="~/Content/bootstrap-datepicker.css" rel="stylesheet" />
        <script src="~/Scripts/jquery-3.1.1.min.js"></script>
        <script src="~/Scripts/bootstrap.min.js"></script>
        <script src="~/Scripts/bootstrap-datepicker.js"></script>
        <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
        <script src="~/Scripts/jquery.validate.min.js"></script>
        <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.2/jquery.validate.unobtrusive.js"></script>
        <script src="~/Scripts/modernizr-2.8.3.js"></script>
     
        <title>Registration</title>
     
    </head>
    <body>
        <div class="container">
            <div class="row">
                <ul class="nav nav-tabs">
      <li role="presentation" class="active"><a href="#">Home</a></li>
      <li role="presentation"><a href="Home/Add">Add</a></li>
      <li role="presentation"><a href="#">Messages</a></li>
    </ul>
            </div>
            <div class="row" style="margin-top: 15px; margin-bottom: 15px;">
                <div class="col-md-8">
                    <div class="input-group" id="adv-search">
                        <input type="text" class="form-control" id="txtsearch" placeholder="Search" />
                        <div class="input-group-btn">
                            <div class="btn-group" role="group">
                                <button type="button" id="searchButton" class="btn btn-primary"><span class="glyphicon glyphicon-search" aria-hidden="true"></span></button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="input-group" id="adv-Add">
                        <div class="input-group-btn">
                            <div class="btn-group" role="group">
     
                                <button type="button" id="btnadd" class="btn btn-primary">Add </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div id="target">
                @Html.Partial("List");
            </div>
        </div>
     
     
        @using (Ajax.BeginForm("Add", "Home", new AjaxOptions
        {
            HttpMethod = "POST",
            UpdateTargetId = "target",
            OnSuccess = "updateSuccess",
     
        }, new { id = "form1" }))
        {
            <div id="Mymodal-Create" class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                                &times;
                            </button>
                            <h4 class="modal-title">Create
                            </h4>
                        </div>
                        <div class="modal-body" id="Create-Body">
                        </div>
     
                        <div class="modal-footer">
                            <input type="Submit" class="btn btn-primary" id="btnsubmit"  value="Add" />
                            <button type="button" class="btn btn-default" data-dismiss="modal">
                                Close
                            </button>
     
                        </div>
     
                    </div>
                    <!-- /.modal-content -->
                </div>
                <!-- /.modal-dialog -->
     
            </div>
        }
        <div id="Mymodal-UserList" class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="listLargeModalLabel" aria-hidden="true">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close close-List">
                                &times;
                            </button>
                            <h4 class="modal-title">Users
                            </h4>
                        </div>
                        <div class="modal-body" id="List-Body">
                        </div>
     
                        <div class="modal-footer">
                            
                            <button type="button" id="close-list" class="btn btn-default close-List">
                                Close
                            </button>
     
                        </div>
     
                    </div>
                    <!-- /.modal-content -->
                </div>
                <!-- /.modal-dialog -->
     
            </div>
     
     
     
        <script type="text/javascript">
            $(function () {
                $('#datepicker').datepicker();
                $(".allownumber").keydown(function (e) {
                    // Allow: backspace, delete, tab, escape, enter and .
                    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
                        // Allow: Ctrl+A, Command+A
                        (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
                        // Allow: home, end, left, right, down, up
                        (e.keyCode >= 35 && e.keyCode <= 40)) {
                        // let it happen, don't do anything
                        return;
                    }
                    // Ensure that it is a number and stop the keypress
                    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                        e.preventDefault();
                    }
                });
                $('#btnadd').click(function () {
                    $.get("Home/Add", function (data) {
                        $("#Create-Body").html(data);
                        $("#Mymodal-Create").modal('show');
     
                    });
                });
                $('#btnsubmit').click(function () {
                    $.validator.unobtrusive.parse("#form1");               
                   // $('#Mymodal-UserList, #Mymodal-Create').modal('hide');
                });
                $('#searchButton').click(function () {
                    $.get("Home/GetUser", { d: $('#txtsearch').val() }, function (data) {
                        $("#target").html(data);
                    });
                });
     
            });
            function updateSuccess(data) {
                $('form')[0].reset();         
                $("#Mymodal-Create").modal('hide');
            }
            $('#close-List').click(function () {
                $("#Mymodal-UserList").modal('hide');
                $("#Mymodal-Create").modal('hide');
             
            });
            function filldata(data) {                  
                $("#Create-Body").html(data);
                $("#Mymodal-UserList").modal('hide');
            };
     
        </script>
     
     
     
    </body>
    </html>

     

    our partial view list code is 

    <link href="~/Content/bootstrap.css" rel="stylesheet" />
    <script src="~/Scripts/bootstrap.js"></script>
    <link href="http://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css" rel="stylesheet" />
    <div class="table table-responsive table-condense">
        <table class="table table-bordered">
            <tr>
                <th>First Name
                </th>
                <th>Middle Name
                </th>
                <th>Last Name
                </th>
                <th>DOB
                </th>
                <th>Mobile
                </th>
                <th>City
                </th>
                <th>Pin
                </th>
                <th>Address
                </th>
                <td></td>
                <td></td>
            </tr>
            @foreach (var d in ViewBag.Users as List<TestSol.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>@Ajax.ActionLink("Edit", "Edit", new { Id = d.Id },
                     new AjaxOptions
                     {
                         InsertionMode = InsertionMode.Replace,
                         HttpMethod = "GET",
                         OnSuccess = "fillUserdata"
                     }) </td>
                    <td>@Ajax.ActionLink("Delete", "Delete", new { Id = d.Id },
                     new AjaxOptions
                     {
                         UpdateTargetId = "target",
                         InsertionMode = InsertionMode.Replace,
                         HttpMethod = "POST"
                     })</td>
     
     
                </tr>
            }
        </table>
     
    </div>
    <script>
        function fillUserdata(data) {              
            $("#Create-Body").html(data);
            $("#Mymodal-Create").modal('show');
      
        }
     
      
     
    </script>
     

     

    When we run our program it will look like this. From search text box we can filter our records.

     

     


    When we click add then it will open in modal pop up it will look like this and it is from Add Partial View

    And code for Add Partial 

    @model TestSol.Models.RegistrationForm
     
    <div class="panel-body">
        @Html.ValidationSummary(false)
        <div class="form-group">
            <div class="row">
                <div class="col-md-4">
                    <div class="input-group" id="adv-search">
                         @Html.HiddenFor(model => model.Id, new {@Value = 0 })
                        @Html.Label("First Name")<br />@Html.TextBoxFor(model => model.FName, new { @class = "form-control", placeholder = "First Name", title = "Enter First Name" })
                        @Html.ValidationMessageFor(model => model.FName)
                      
                        <div class="input-group-btn">
                            <div class="btn-group" role="group">
                                <button type="button" id="btnbrowse" class="btn btn-primary" style="margin-top: 23px"><span class="glyphicon glyphicon-search" aria-hidden="true"></span></button>
                            </div>
                        </div>
                    </div>
                </div>
     
                <div class="col-md-4">
                    @Html.Label("Middle Name")<br />@Html.TextBoxFor(model => model.MName, new { @class = "form-control", placeholder = "Middle Name", title = "Enter Middle Name" })
                </div>
                <div class="col-md-4">
                    @Html.Label("Last Name")<br />@Html.TextBoxFor(model => model.LName, new { @class = "form-control", placeholder = "Last Name", title = "Enter Last Name" })
                </div>
            </div>
            <div class="row">
                <div class="col-md-4">
                    @Html.Label("DOB")<br />
                    @Html.TextBoxFor(model => model.Dob, new { @class = "form-control ", id = "datepicker", placeholder = "Dob", title = "Enter DOB", @value = Model != null && Model.Dob != null ? Model.Dob.ToString("dd/MM/yyyy") : null })
                </div>
                <div class="col-md-4">
                    @Html.Label("Mobile Number")<br />@Html.TextBoxFor(model => model.Mobile, new { @class = "form-control allownumber", placeholder = "Mobile", title = "Enter Mobile", @maxlength = "10" })
                </div>
                <div class="col-md-4">
                    @Html.Label("City")<br />@Html.DropDownListFor(model => model.City, new SelectList(ViewBag.Country, "Country", "Country"),
        "Select Category", new { @class = "form-control", placeholder = "City", title = "Enter City" })
                </div>
            </div>
            <div class="row">
                <div class="col-md-4">
                    @Html.Label("Pin")<br />@Html.TextBoxFor(model => model.Pin, new { @class = "form-control allownumber", placeholder = "Pin", title = "Enter Pin", @maxlength = "6" })@Html.ValidationMessageFor(model => model.Pin)
                </div>
                <div class="col-md-4">
                    @Html.Label("Address")<br />@Html.TextAreaFor(model => model.Address, new { @class = "form-control", placeholder = "Address", title = "Enter Address" })
                </div>
            </div>
     
        </div>
     
    </div>
     
     
    <script>
        $(function () {
            $('#datepicker').datepicker();
        });
        $('#btnbrowse').click(function () {
            $.get("Home/GetRecord", function (data) {
                $("#List-Body").html(data);         
                $("#Mymodal-UserList").modal('show');
             
            });
        });
        $('#close-list').click(function () {
            $("#Mymodal-UserList").modal('hide');
          
        });
    </script>




     When we click edit It will return partial Userlist in the pop up .Code for Userlist 

    <link href="~/Content/bootstrap.css" rel="stylesheet" />
    <script src="~/Scripts/bootstrap.js"></script>
    <link href="http://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css" rel="stylesheet" />
    <div class="table table-responsive table-condense">
        <table class="table table-bordered">
            <tr>
                <th>First Name
                </th>
                <th>Middle Name
                </th>
                <th>Last Name
                </th>
                <th>DOB
                </th>
                <th>Mobile
                </th>
     
            </tr>
            @foreach (var d in ViewBag.Users as List<TestSol.Models.RegistrationForm>)
            {
                <tr>
                    <td>@d.FName</td>
                    <td>@d.MName</td>
                    <td>@d.LName</td>
                    <td>@d.Mobile</td>
                    <td>@Ajax.ActionLink("Select", "Edit", new { Id = d.Id },
                     new AjaxOptions
                     {
                         InsertionMode = InsertionMode.Replace,
                         HttpMethod = "GET",
                         OnSuccess = "filldata"// <-- HTTP method
                     }) </td>
     
     
                </tr>
            }
        </table>
       
    </div>

     

      

     

    Thank you.. 

     

     

     

     

     

      Modified On Apr-11-2018 10:44:03 PM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!