Look at the following image:
MVC Project Prerequeste:
MVC Project Prerequeste:
- Create a MVC4/5 project in VB 2010/2012/2013.
- Add an Entity Framework 5/6.
Create MVC5 Project
1.Create a new "ASP.NET Web Application" project.
2.Name it MVCEFDM.
3.Provide a Project Location in Local Host/Disk Drive and click Ok.
4.Select the MVC From Project Option.
It will create a new MVC5 project with Entity Framework 5/6 already installed, if it is not installed then install it from the nuGet Repository from: NuGet.
Database design
Database design
1.Create a database for performing CRUD operations on only one table.
2.The schema of the Employee table is as below.
Create Data Model
- Right-click on the Model and select "Add | New Item..." .
- From the Data tab select ADO.Net Entity Data Model.
- Provide the name of the EntityModel as “EmployeeModel” and click the Add button.
- You will get a dialog box. From there select the "Generate from database" option.
- Create a new connection that includes the senstive data in it / or Not option.
- ByDefault It will create a database name as in the following logic.
Database name + Entities = default connection setting name - Open Web.config to see the connection string and see that it will create a new connection string with the information as:
name: name of connection string for entity dbStudentEntities.
meta data with
Models.EmployeeModel.csdl|res://*/Models.EmployeeModel.ssdl|res://*/Models.EmployeeModel.msl;
Data Sources: Terminal10
initial catalog: dbStudent
And App=EntityFramework"" providerName="System.Data.EntityClient" and so on. - The complete Connection String is:
- <add name="dbStudentEntities" connectionString="metadata=res://*/Models.EmployeeModel.csdl|res://*/Models.EmployeeModel.ssdl|res://*/Models.EmployeeModel.msl;provider=System.Data.SqlClient;provider connection string="data source=Terminal10;initial catalog=dbStudent;user id=sa;password=sa;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
- Now you need to choose the data objects to make them a part of the Data Model. From the dialog box you can choose tables, Stored Procedures and views.
Select Employee table to perfrom CRUD operations only on this.
The Model namespace name by default would be the database name suffixed with Model.
Now click Finish to create the data model as EmployeeModel.edmx. - Create a Layout.cshtml page in the View/Shared folder...
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width" />
- <title>@ViewBag.Title</title>
- @Styles.Render("~/Content/css")
- @Scripts.Render("~/bundles/modernizr")
- </head>
- <body>
- @RenderBody()
- @Scripts.Render("~/bundles/jquery")
- @RenderSection("scripts", required: false)
- </body>
- </html>
- @{
- Layout = null;
- }
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Error</title>
- </head>
- <body>
- <hgroup>
- <h1>Error.</h1>
- <h2>An error occurred while processing your request.</h2>
- </hgroup>
- </body>
- </html>
- @{
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
Performing CRUD operation
[Model] : EmployeeModel
It consists of the 2 main Files EmployeeModel.Context.tt and EmployeeModel.tt.
In EmployeeModel.Context.tt – It consists of EmployeeModel.Context.cs
EmployeeModel.Context.cs:
It consists of a dbStudentEntities class for the connection string context.
[Model] : EmployeeModel
It consists of the 2 main Files EmployeeModel.Context.tt and EmployeeModel.tt.
In EmployeeModel.Context.tt – It consists of EmployeeModel.Context.cs
EmployeeModel.Context.cs:
It consists of a dbStudentEntities class for the connection string context.
- namespace MVCEFDM.Models
- {
- using System;
- using System.Data.Entity;
- using System.Data.Entity.Infrastructure;
- public partial class dbStudentEntities : DbContext
- {
- public dbStudentEntities() : base("name=dbStudentEntities")
- {
- }
- protected override void OnModelCreating(DbModelBuilder modelBuilder)
- {
- throw new UnintentionalCodeFirstException();
- }
- public DbSet<Employee> Employees { get; set; }
- }
- }
Employee.cs : Employee Model
- namespace MVCEFDM.Models
- {
- using System;
- using System.Collections.Generic;
- public partial class Employee
- {
- public int Id { get; set; }
- public string Id1 { get; set; }
- public string Name { get; set; }
- public string desig { get; set; }
- public string salary { get; set; }
- }
- }
Creating Controller
Step 1
Step 1
Right-click on the Controller, Select Controller. It will open an Add Scaffold window.
Step 2
Step 2
Select MVC5 Controller with views, using Entity Framework.
Step 3
Step 3
It will automatically create a Controller with all the necessary operations.
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Data.Entity;
- using System.Linq;
- using System.Net;
- using System.Web;
- using System.Web.Mvc;
- using MVCEFDM.Models;
- namespace MVCEFDM.Controllers
- {
- public class EmployeesController : Controller
- {
- private dbStudentEntities db = new dbStudentEntities();
- // GET: Employees
- public ActionResult Index()
- {
- return View(db.Employees.ToList());
- }
- // GET: Employees/Details/5
- public ActionResult Details(int? id)
- {
- if (id == null)
- {
- return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
- }
- Employee employee = db.Employees.Find(id);
- if (employee == null)
- {
- return HttpNotFound();
- }
- return View(employee);
- }
- // GET: Employees/Create
- public ActionResult Create()
- {
- return View();
- }
- // POST: Employees/Create
- // To protect from overposting attacks, please enable the specific properties you want to bind to, for
- // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult Create([Bind(Include = "Id,Id1,Name,desig,salary")] Employee employee)
- {
- if (ModelState.IsValid)
- {
- db.Employees.Add(employee);
- db.SaveChanges();
- return RedirectToAction("Index");
- }
- return View(employee);
- }
- // GET: Employees/Edit/5
- public ActionResult Edit(int? id)
- {
- if (id == null)
- {
- return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
- }
- Employee employee = db.Employees.Find(id);
- if (employee == null)
- {
- return HttpNotFound();
- }
- return View(employee);
- }
- // POST: Employees/Edit/5
- // To protect from overposting attacks, please enable the specific properties you want to bind to, for
- // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult Edit([Bind(Include = "Id,Id1,Name,desig,salary")] Employee employee)
- {
- if (ModelState.IsValid)
- {
- db.Entry(employee).State = EntityState.Modified;
- db.SaveChanges();
- return RedirectToAction("Index");
- }
- return View(employee);
- }
- // GET: Employees/Delete/5
- public ActionResult Delete(int? id)
- {
- if (id == null)
- {
- return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
- }
- Employee employee = db.Employees.Find(id);
- if (employee == null)
- {
- return HttpNotFound();
- }
- return View(employee);
- }
- // POST: Employees/Delete/5
- [HttpPost, ActionName("Delete")]
- [ValidateAntiForgeryToken]
- public ActionResult DeleteConfirmed(int id)
- {
- Employee employee = db.Employees.Find(id);
- db.Employees.Remove(employee);
- db.SaveChanges();
- return RedirectToAction("Index");
- }
- protected override void Dispose(bool disposing)
- {
- if (disposing)
- {
- db.Dispose();
- }
- base.Dispose(disposing);
- }
- }
- }
Step 4
It will automatically create a View for performing CRUD operations.
Create.cshtml
Create.cshtml
- @model MVCEFDM.Models.Employee
- @{
- ViewBag.Title = "Create";
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
- <h2>Create</h2>
- @using (Html.BeginForm())
- {
- @Html.AntiForgeryToken()
- <div class="form-horizontal">
- <h4>Employee</h4>
- <hr />
- @Html.ValidationSummary(true, "", new { @class = "text-danger" })
- <div class="form-group">
- @Html.LabelFor(model => model.Id, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Id, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.Id, "", new { @class = "text-danger" })
- </div>
- </div>
- <div class="form-group">
- @Html.LabelFor(model => model.Id1, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Id1, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.Id1, "", new { @class = "text-danger" })
- </div>
- </div>
- <div class="form-group">
- @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
- </div>
- </div>
- <div class="form-group">
- @Html.LabelFor(model => model.desig, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.desig, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.desig, "", new { @class = "text-danger" })
- </div>
- </div>
- <div class="form-group">
- @Html.LabelFor(model => model.salary, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.salary, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.salary, "", new { @class = "text-danger" })
- </div>
- </div>
- <div class="form-group">
- <div class="col-md-offset-2 col-md-10">
- <input type="submit" value="Create" class="btn btn-default" />
- </div>
- </div>
- </div>
- }
- <div>
- @Html.ActionLink("Back to List", "Index")
- </div>
- @section Scripts {
- @Scripts.Render("~/bundles/jqueryval")
- }
- @model MVCEFDM.Models.Employee
- @{
- ViewBag.Title = "Delete";
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
- <h2>Delete</h2>
- <h3>Are you sure you want to delete this?</h3>
- <div>
- <h4>Employee</h4>
- <hr />
- <dl class="dl-horizontal">
- <dt>
- @Html.DisplayNameFor(model => model.Id1)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.Id1)
- </dd>
- <dt>
- @Html.DisplayNameFor(model => model.Name)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.Name)
- </dd>
- <dt>
- @Html.DisplayNameFor(model => model.desig)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.desig)
- </dd>
- <dt>
- @Html.DisplayNameFor(model => model.salary)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.salary)
- </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>
@model MVCEFDM.Models.Employee
- @{
- ViewBag.Title = "Details";
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
- <h2>Details</h2>
- <div>
- <h4>Employee</h4>
- <hr />
- <dl class="dl-horizontal">
- <dt>
- @Html.DisplayNameFor(model => model.Id1)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.Id1)
- </dd>
- <dt>
- @Html.DisplayNameFor(model => model.Name)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.Name)
- </dd>
- <dt>
- @Html.DisplayNameFor(model => model.desig)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.desig)
- </dd>
- <dt>
- @Html.DisplayNameFor(model => model.salary)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.salary)
- </dd>
- </dl>
- </div>
- <p>
- @Html.ActionLink("Edit", "Edit", new { id = Model.Id }) |
- @Html.ActionLink("Back to List", "Index")
- </p>
- @model MVCEFDM.Models.Employee
- @{
- ViewBag.Title = "Edit";
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
- <h2>Edit</h2>
- @using (Html.BeginForm())
- {
- @Html.AntiForgeryToken()
- <div class="form-horizontal">
- <h4>Employee</h4>
- <hr />
- @Html.ValidationSummary(true, "", new { @class = "text-danger" })
- @Html.HiddenFor(model => model.Id)
- <div class="form-group">
- @Html.LabelFor(model => model.Id1, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Id1, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.Id1, "", new { @class = "text-danger" })
- </div>
- </div>
- <div class="form-group">
- @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
- </div>
- </div>
- <div class="form-group">
- @Html.LabelFor(model => model.desig, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.desig, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.desig, "", new { @class = "text-danger" })
- </div>
- </div>
- <div class="form-group">
- @Html.LabelFor(model => model.salary, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.salary, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.salary, "", new { @class = "text-danger" })
- </div>
- </div>
- <div class="form-group">
- <div class="col-md-offset-2 col-md-10">
- <input type="submit" value="Save" class="btn btn-default" />
- </div>
- </div>
- </div>
- }
- <div>
- @Html.ActionLink("Back to List", "Index")
- </div>
- @section Scripts {
- @Scripts.Render("~/bundles/jqueryval")
- }
- @model IEnumerable<MVCEFDM.Models.Employee>
- @{
- ViewBag.Title = "Index";
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
- <h2>Index</h2>
- <p>
- @Html.ActionLink("Create New", "Create")
- </p>
- <table class="table">
- <tr>
- <th>
- @Html.DisplayNameFor(model => model.Id1)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.Name)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.desig)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.salary)
- </th>
- <th></th>
- </tr>
- @foreach (var item in Model) {
- <tr>
- <td>
- @Html.DisplayFor(modelItem => item.Id1)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.Name)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.desig)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.salary)
- </td>
- <td>
- @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
- @Html.ActionLink("Details", "Details", new { id=item.Id }) |
- @Html.ActionLink("Delete", "Delete", new { id=item.Id })
- </td>
- </tr>
- }
- </table>
No comments :
Post a Comment