How to update and delete a record from the database using MVC

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<Friend> Friend { get; set; }
}
}



The Controller

// 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(); } } To add a record to the database, i used the following code. It worked;
            myEntities.Friend.Add(f);
            myEntities.SaveChanges();
            return RedirectToAction("Index");
 
 
UPDATE

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Exp.Models.Friend>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
 
 
 Delete
 
 </asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<h2>Delete</h2>

<h3>Are you sure you want to delete?</h3>
<fieldset>
    <legend>Friend</legend>

    <div class="display-label">Name</div>
    <div class="display-field">
        <%: Html.DisplayFor(model => model.Name) %>
    </div>


</fieldset>
<% using (Html.BeginForm()) { %>
    <p>
        <input type="submit" value="Delete" /> |
        <%: Html.ActionLink("Back to List", "Index") %>
    </p>
<% } %>

</asp:Content>
 
 
 
 
Delete


myEntities.Friend.Remove(f);
myEntities.SaveChanges();
 
 
Update

Friend f = myEntities.Friend.FirstOrDefault(x => x.Id = MyId);
f.Name = NewName;
myEntities.SaveChanges();
To update, it's the same as add but without the .Friend.Add(f). Load the item like so:

var friendEntity = myEntites.Friend.SingleOrDefault(f => f.Id == id);
friendEntity.Field1 = f.Field1;
...
myEntities.SaveChanges();
 
Update:

if (ModelState.IsValid && f != null) { myEntities.Friend.Attach(f); var upd = (from c in myEntities.Friend where c.Id == f.Id select c).FirstOrDefault(); upd.Data1=f.Data1; ... .... myEntities.ObjectStateManager.ChangeObjectState(f, EntityState.Modified); myEntities.SaveChanges(); }


Delete:

   if (ModelState.IsValid && f != null)
        {
            var del = (from c in myEntities.Friend
                       where c.Id == f.Id
                       select c).FirstOrDefault();

            myEntities.Friend.DeleteObject(del);
            myEntities.SaveChanges();
        }