crud operation in mvc using data annotation with entity framework .

Total Post:27

Points:189
Mvc  Mvc4 
 884  View(s)
Ratings:
Rate this:
i am beginer in mvc how to complete .crud operation in mvc using data annotation with entity framework . please help me any one.
  1. Post:52

    Points:366
    Re: crud operation in mvc using data annotation with entity framework .

    here i am giving code for crud operation in mvc using data annotation with entity framework . i hope this will help to you.

    First Create a database and table



    Adding the validation attributes

    directly to the model class works when you do not expect the database to

    change; however, if your database changes and you need to regenerate the model

    class, you will lose all of the attributes you had applied to the model class.

    This approach can be very inefficient and prone to losing important validation

    rules.

    To avoid this problem, you can 

    add a metadata class that contains the attributes. When you associate the model

    class to the metadata class, those attributes are applied to the model. In this

    approach, the model class can be regenerated without losing all of the

    attributes that have been applied to the metadata class.In the Models folder,

    add a class named Metadata.cs.

    using System;
    

    using System.Collections.Generic;

    using System.Linq;

    using System.Web;

    using System.ComponentModel.DataAnnotations;

    namespace Demo.Models

    {

        public class EmpDetailMetaData

        {

            [Required(ErrorMessage = "UserName Name is required")]

            public string UserName { get; set; }

            [Required(ErrorMessage = "FName Name is required")]

            public string FName { get; set; }

            [Required(ErrorMessage = "Email is required")]

            public string Email { get; set; }

            [Required(ErrorMessage = "Mobile is required")]

            public string Mobile { get; set; }

        }

    }

    These metadata classes contain all of the validation attributes that you had previously applied to the model classes. The Display attribute is used to change the value used for text labels. 

    Now, you must associate the model classes with the metadata classes.In the Models folder,

    add a class named PartialClass.cs.

    using System;
    
    using System.Collections.Generic;

    using System.Linq;

    using System.Web;

    using System.ComponentModel.DataAnnotations;

    namespace Demo.Models

    {

            [MetadataType(typeof(EmpDetailMetaData))]

            public partial class EmpDetail

            {

            }

    }

    Implement a Generic Repository and a Unit of Work Class 

    Creating a repository class for

    each entity type could result in a lot of redundant code, and it could result

    in partial updates. For example, suppose you have to update two different

    entity types as part of the same transaction. If each uses a separate database

    context instance, one might succeed and the other might fail. One way to

    minimize redundant code is to use a generic repository, and one way to ensure

    that all repositories use the same database context (and thus coordinate all updates)

    is to use a unit of work class.

    In this section of the tutorial, you'll create a GenericRepository class

    and a UnitOfWork class, and use them in the Course controller

    to access both the Department and the Course entity sets. As explained earlier, to keep this part

    of the tutorial simple, you aren't creating interfaces for these classes. But

    if you were going to use them to facilitate TDD, you'd typically implement them

    with interfaces the same way you did the Student repository.

    Create and emty project  

    And for generic repository

    In the Models Folder add a class

    IRepository


    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Web;

    using Demo.Models;



    namespace Demo.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);

        }

    }

    And

    add another class Repository and inherit IRepository

    using System;
    using
    System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using Demo.Models;
    using System.Data.Entity;
    using System.Data;
    namespace Demo.Models
    {
        public class Reposiroty<T> : IRepository<T> where T : class
        {
            private Entities db = null;
            private DbSet<T> table = null;
            public Reposiroty()
            {
                this.db = new Entities();
                table = db.Set<T>();
            }
            public Reposiroty(Entities 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();
            }
        }
    }

    For working with unit of Work

    Add base controller in

    Controllers Folder

    using Demo.Models;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    namespace Demo.Controllers
    {
        public class BaseController : Controller
        {
            protected DMLRepository Uow { get; set; }
            private Entities db = null;
            public BaseController()
            {
                Uow = new DMLRepository();
            }
        }
    }

    And then Add home Controller

    in Cotrollers Folder for all operation and inherit base controller in it

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using Demo.Models;
    namespace Demo.Controllers
    {
        public class HomeController : BaseController
        {
           public ActionResult Index()
            {
                ViewBag.Users =
    Uow.EmpDetail.SelectAll();
                return View();
            }
        [AcceptVerbs(HttpVerbs.Post)]
            public ActionResult Index(EmpDetail model)
            {
                if (ModelState.IsValid)
                {
                    if (model.Id == 0)
                    {
                        Uow.EmpDetail.Insert(model);
                    }
                    else
                    {
                        var data = Uow.EmpDetail.SelectByID(model.Id);
                        if (data == null)
                         Uow.EmpDetail.Insert(model);
                        else
                        Uow.EmpDetail.Update(model);
                    }
                }
                    ViewBag.Users =Uow.EmpDetail.SelectAll();
                    return PartialView("UserList");
          }
            [HttpPost]
            public ActionResult Delete(int Id)
            {
                Uow.EmpDetail.Delete(Id);
                ViewBag.Users = Uow.EmpDetail.SelectAll();
                return PartialView("UserList");
            }
            public ActionResult Edit(int Id)
            {
                var data = Uow.EmpDetail.SelectByID(Id);
                return Json(data, JsonRequestBehavior.AllowGet);
            }
        }
    }

    And add view index

    @model
    Demo.Models.EmpDetail
    @{
        ViewBag.Title = "Index";
    }
    <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.2/jquery.validate.unobtrusive.js"></script>
    @using (Ajax.BeginForm("index", "Home", new AjaxOptions
    {
        HttpMethod = "POST",
        UpdateTargetId = "target",
        OnSuccess = "updateSuccess"
    }))
    {
            <center><h2>Registration Form</h2></center>
         @Html.ValidationSummary(true)
            <hr />
           <div>
                <center> <table border="0" width="70%" cellspadding="0" cellspacing="0">
            <tr>
                 <td><label id="label1">User Name</label>
                    @Html.HiddenFor(x => x.Id, new {@Value=0 })
                </td>
                  <td>@Html.TextBoxFor(x =>x.UserName)
                      @Html.ValidationMessageFor(m=> m.UserName)
                  </td>
                <td><label id="label2">Father Name</label></td>
                  <td>@Html.TextBoxFor(x =>x.FName)
                      @Html.ValidationMessageFor(m=> m.FName)
                  </td>
            </tr>
           <tr>
                <td><label id="label3">Email</label></td>
                  <td>@Html.TextBoxFor(x =>x.Email)
                      @Html.ValidationMessageFor(m=> m.Email)
                  </td>
                <td><label id="label4">Mobile</label></td>
                  <td>@Html.TextBoxFor(x =>x.Mobile)
                      @Html.ValidationMessageFor(m=> m.Mobile)
                  </td>
            </tr>
           <tr>
             <td colspan="2"> <br /> <center>
                   <input type="submit" value="Submit" /></center>
               </td>
           </tr>
        </table></center>
            </div>
    }
       <div id="target">
        @Html.Partial("UserList");
        </div>
    <script>
        function updateSuccess(data)
        {
            $('form')[0].reset();
        }
    </script>

    And partial view

    <table border="1" cellspacing="0" cellpadding="5" style="width: 60%; margin-left: 20%">
                <tr>
                    <th>Name</th>
                    <th>Emailid</th>
                </tr>
                @foreach (var d in ViewBag.Users as List<Demo.Models.EmpDetail>)
                {
                    <tr>
                        <td>@d.UserName</td>
                        <td>@d.Email</td>
                        <td>
                     @Ajax.ActionLink("Edit", "Edit",new{Id=d.Id},
                     new AjaxOptions
                     {
                         InsertionMode = InsertionMode.Replace,
                         HttpMethod = "GET",
                         OnSuccess = "filldata"//
    <-- HTTP method
                     }) |
                     @Ajax.ActionLink("Delete", "Delete",new{Id=d.Id},
                     new AjaxOptions
                     {
                         UpdateTargetId = "target",
                         InsertionMode = InsertionMode.Replace,
                         HttpMethod = "POST"
                     })
                        </td>
                    </tr>
                }
            </table>
        <script>
            function filldata(data) {
            $('#UserName').val(data.UserName);
            $('#Id').val(data.Id);
            $('#FName').val(data.FName);
            $('#Email').val(data.Email);
            $('#Mobile').val(data.Mobile);
        }
        </script>


    thanks.


      Modified On Apr-11-2018 06:13:46 AM

Answer