title: C# - MVC application How to update and delete a record from the database
body: <p>I need to know how to update and delete a record from the database. I know how to add a record but unable to update and delete a record to the database.</p>
  
  <pre><code>namespace Ex.Models
  {
      using System;
      using System.Data.Entity;
      using System.Data.Entity.Infrastructure;
  
      public partial class MyEntities : DbContext
      {
          public MyEntities()
              : base("name= MyEntities")
          {
          }
  
          protected override void OnModelCreating(DbModelBuilder modelBuilder)
          {
              throw new UnintentionalCodeFirstException();
          }
  
          public DbSet&lt;Friend&gt; Friend { get; set; }
      }
  }
  </code></pre>
  
  <p>--</p>
  
  <p>The Controller</p>
  
  <pre><code>// POST: /Home/Edit/5
  [HttpPost]
  public ActionResult Edit(int id, Friend f)
  {
      try
      {
          // TODO: Add update logic here
          myEntities.Friend.Attach(f);// Doesn't work.. How to update ?
          myEntities.SaveChanges();
          return RedirectToAction("Index");
      }
      catch
      {
          return View();
      }
  }
  </code></pre>
  
  <p>To add a record to the database, i used the following code. It worked;</p>
  
  <pre><code>myEntities.Friend.Add(f);
  myEntities.SaveChanges();
  return RedirectToAction("Index");
  </code></pre>
  
  <p>UPDATE</p>
  
  <pre><code>&lt;%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage&lt;Exp.Models.Friend&gt;" %&gt;
  
  &lt;asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"&gt;
      Delete
  &lt;/asp:Content&gt;
  
  &lt;asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"&gt;
  
  &lt;h2&gt;Delete&lt;/h2&gt;
  
  &lt;h3&gt;Are you sure you want to delete?&lt;/h3&gt;
  &lt;fieldset&gt;
      &lt;legend&gt;Friend&lt;/legend&gt;
  
      &lt;div class="display-label"&gt;Name&lt;/div&gt;
      &lt;div class="display-field"&gt;
          &lt;%: Html.DisplayFor(model =&gt; model.Name) %&gt;
      &lt;/div&gt;
  
  
  &lt;/fieldset&gt;
  &lt;% using (Html.BeginForm()) { %&gt;
      &lt;p&gt;
          &lt;input type="submit" value="Delete" /&gt; |
          &lt;%: Html.ActionLink("Back to List", "Index") %&gt;
      &lt;/p&gt;
  &lt;% } %&gt;
  
  &lt;/asp:Content&gt;
  </code></pre>