Sunday, November 10, 2019

Code First Approach in Ado.net entity framework

Code First Approach:


First Create new project in Visual studio 2019

    1. Right Click on Solution Explore -> Add -> New Projects -> Select Asp.Net Web Application(.Net Framework) using C# code ->Next ->Project Name(CodeFirstApproach) ->Create

     2. Select a template -> Empty -> Check MVC -> ok.

Project is created with MVC folder



Step 1: Add Entity

Right click on references -> Manage NuGet Packages -> Browse -> click EntityFramework -> Install


Now added the entity framework in references folder.

Step 2: Create model class

Right click on Models folder -> Add -> Class -> Name (EmployeeModel.cs) ->ok, its created a EmployeeModel.cs and type the following code:

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

namespace CodeFirstApproach.Models
{
    public class EmployeeModel
    {
        [Key]
        public int EmpId { get; set; }
        public string EmpName { get; set; }
        public int EmpSalary { get; set; }
    }
}

Add one more class like EmployeeContext.cs and type following code

using System.Data.Entity;

namespace CodeFirstApproach.Models
{
    public class EmployeeContext : DbContext
    {
        public EmployeeContext() : base(“Constr”)
        {
        }
        public DbSet<EmployeeModel> EmployeeModels { get; set; }

    }
}

Now, this DbContext will do many things for us such as it will create databases and tables. You can check your newly added database file.

DbSet: This class represents an entity set that is used for the CRUD operations.

Connection string in web.config

  <connectionStrings>
    <add name="Constr" connectionString="Data Source=LENOVO-PC; Initial Catalog=CodeFirstApproach; UID=sa; pwd=likhil@2013;" providerName="System.Data.Sqlclient"/>
  </connectionStrings>

Step 3: Add Controller

Right click on controllers folder -> Add -> Controller -> MVC5 Controller – Empty -> Add -> Name(EmployeeController.cs) -> Add

Past the below code in EmployeeController.cs page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CodeFirstApproach.Models;

namespace CodeFirstApproach.Controllers
{
    public class EmployeeController : Controller
    {
        public EmployeeContext db = new EmployeeContext();
        // GET: Employee
        public ActionResult Index()
        {
            return View(db.EmployeeModels.ToList());
        }
        [HttpGet]
        public ActionResult Create()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Create(EmployeeModel emp)
        {
            db.EmployeeModels.Add(emp);
            int i = db.SaveChanges();
            if (i > 0)
            {
                return RedirectToAction("Index");
            }
            else
            {
                return View();
            }
        }
        [HttpGet]

        public ActionResult Edit(int? Id)

        {

            EmployeeModel obj = db.EmployeeModels.Find(Id);

            return View(obj);

        }

        [HttpPost]

        public ActionResult Edit(EmployeeModel emp)

        {

            if (ModelState.IsValid)

            {

                db.Entry(emp).State = EntityState.Modified;

                db.SaveChanges();

                return RedirectToAction("Index");

            }

            return View(emp);

        }

        [HttpGet]

        public ActionResult Details(int? id)

        {

            EmployeeModel employeeModel = db.EmployeeModels.Find(id);

            return View(employeeModel);

        }



        [HttpGet]

        public ActionResult Delete(int? Id)

        {

            return View();

        }

        [HttpPost]

        [ActionName("Delete")]

        public ActionResult Deleteconform(int? Id)

        {

            EmployeeModel employeeModel = db.EmployeeModels.Find(Id);

            db.EmployeeModels.Remove(employeeModel);

            db.SaveChanges();

            return RedirectToAction("Index");

        }
    }
}

Step 4: Add Views

Right Click on Index method in EmployeeController.cs page -> Add View -> add view template will be open don’t change any thing then click Add, then copy the following code in Index.cshtml page

@model List<CodeFirstApproach.Models.EmployeeModel>
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<table>
    <tr>
        <th>EmpId</th>
        <th>EmpName</th>
        <th>EmpSalary</th>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>@item.EmpId</td>
            <td>@item.EmpName</td>
            <td>@item.EmpSalary</td>
        </tr>
    }
</table>

Copy code in Create.cshtml page


@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm())
{
    @Html.Label("EmpName");
    @Html.TextBox("EmpName");
    <br />
    @Html.Label("EmpSalary");
    @Html.TextBox("EmpSalary");
    <br />
    <input type="submit" value="Save" class="btn btn-success" />
}

Copy code in Edit.cshtml page

@model CodeFirstApproach.Models.EmployeeModel



@{

    ViewBag.Title = "Edit";

}



<h2>Edit</h2>



@using (Html.BeginForm())

{

    @Html.Hidden("EmpId", Model.EmpId)

    @Html.Label("EmpName")

    @Html.TextBox("EmpName", Model.EmpName)

    <br />

    @Html.Label("EmpSalary")

    @Html.TextBox("EmpSalary", Model.EmpSalary)

    <br />

    <input type="submit" value="Save" class="btn btn-default" />   

}



<div>

    @Html.ActionLink("Back to List", "Index")

</div>

Right click on Details method in EmployeeController.cs page then click add view, its show the dailog box like below


You Select the details like above then click Add button, it will genarated Details.cshtml page like below.


@model CodeFirstApproach.Models.EmployeeModel

@{

    ViewBag.Title = "Details";

}



<h2>Details</h2>


<div>

    <h4>EmployeeModel</h4>

    <hr />

    <dl class="dl-horizontal">

        <dt>

            @Html.DisplayNameFor(model => model.EmpName)

        </dt>



        <dd>

            @Html.DisplayFor(model => model.EmpName)

        </dd>



        <dt>

            @Html.DisplayNameFor(model => model.EmpSalary)

        </dt>



        <dd>

            @Html.DisplayFor(model => model.EmpSalary)

        </dd>



    </dl>

</div>

<p>

    @Html.ActionLink("Edit", "Edit", new { id = Model.EmpId }) |

    @Html.ActionLink("Back to List", "Index")

</p>

Right click on Delete method in EmployeeController.cs page then click add view, its show the dailog box like below


You Select the details like above then click Add button, it will genarated Delete.cshtml page like below.

@model CodeFirstApproach.Models.EmployeeModel

@{
    ViewBag.Title = "Delete";
}

<h2>Delete</h2>

<h3>Are you sure you want to delete this?</h3>
<div>
    <h4>EmployeeModel</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.EmpName)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.EmpName)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.EmpSalary)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.EmpSalary)
        </dd>

    </dl>

    @using (Html.BeginForm()) {
        @Html.AntiForgeryToken()

        <div class="form-actions no-color">
            <input type="submit" value="Delete" class="btn btn-default" /> |
            @Html.ActionLink("Back to List", "Index")
        </div>
    }
</div>



No comments:

Post a Comment