Introduction : This Tutorial explain how to perform insert,update ,delete operation using the entityframwork in mvc4 web application
Tools: Visual studio 2012 and Sql server
Step 1 : Create Ado.net Entity Data model
Step 2 : Select data modal from the database as following
Step 3 : then submit finish
Step 4: Add Controller as below
Step5 : when you add controller crud code can be added as folowing :
public ActionResult Details(int id = 0)
{
tbl_user tbl_user = db.tbl_user.Find(id);
if (tbl_user == null)
{
return HttpNotFound();
}
return View(tbl_user);
}
//
// GET: /ABC/Create
public ActionResult Create()
{
return View();
}
//
// POST: /ABC/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(tbl_user tbl_user)
{
if (ModelState.IsValid)
{
db.tbl_user.Add(tbl_user);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(tbl_user);
}
//
// GET: /ABC/Edit/5
public ActionResult Edit(int id = 0)
{
tbl_user tbl_user = db.tbl_user.Find(id);
if (tbl_user == null)
{
return HttpNotFound();
}
return View(tbl_user);
}
//
// POST: /ABC/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(tbl_user tbl_user)
{
if (ModelState.IsValid)
{
db.Entry(tbl_user).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(tbl_user);
}
//
// GET: /ABC/Delete/5
public ActionResult Delete(int id = 0)
{
tbl_user tbl_user = db.tbl_user.Find(id);
if (tbl_user == null)
{
return HttpNotFound();
}
return View(tbl_user);
}
//
// POST: /ABC/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
tbl_user tbl_user = db.tbl_user.Find(id);
db.tbl_user.Remove(tbl_user);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
After adding controller you can see view as following
<h2>Create</h2>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>tbl_user</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Address)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Address)
@Html.ValidationMessageFor(model => model.Address)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Phone)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Phone)
@Html.ValidationMessageFor(model => model.Phone)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
Now Run the Project and see o/p and the code
Sign up here with your email
ConversionConversion EmoticonEmoticon