4

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.

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>
JJS
  • 6,431
  • 1
  • 54
  • 70
Sharon Watinsan
  • 9,620
  • 31
  • 96
  • 140

6 Answers6

9

Delete

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

Update

Friend f = myEntities.Friend.FirstOrDefault(x => x.Id = MyId);
f.Name = NewName;
myEntities.SaveChanges();
Alexandr Sulimov
  • 1,894
  • 2
  • 24
  • 48
  • What is the difference between using `SingleOrDefault ` and `FirstOrDefault ` ? – Sharon Watinsan Jan 09 '13 at 08:28
  • http://stackoverflow.com/questions/1745691/linq-when-to-use-singleordefault-vs-firstordefault-with-filtering-criteria – Alexandr Sulimov Jan 09 '13 at 08:52
  • I solved the Update part. But when i click on delete i am taken to another page, where it will display the records that i chosed to delete and will ask if i want to delete the said record. In this page the record i want to delete is not shown therefore i get an error. Any idea how i could solve this ? I have updated my code above. – Sharon Watinsan Jan 09 '13 at 09:35
3

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();

To delete, use the opposite of .Add(f), .Remove.

Paul Fleming
  • 24,238
  • 8
  • 76
  • 113
  • Is there a mistake at `f=>` and `myEntities.SaveChanges();` ? – Sharon Watinsan Jan 09 '13 at 08:22
  • I didn't test this code, it's freehand. If you don't know already `=>` is the syntax for a [lambda expression](http://msdn.microsoft.com/en-us/library/bb397687.aspx). – Paul Fleming Jan 09 '13 at 08:25
  • `Error 1 A local variable named 'f' cannot be declared in this scope because it would give a different meaning to 'f', which is already used in a 'parent or current' scope to denote something else ` This is what i get. i am a bit new to C# – Sharon Watinsan Jan 09 '13 at 08:26
  • Ah, yes, change it to something else. Say `e` for "entity" or `f1`. – Paul Fleming Jan 09 '13 at 08:40
  • and, Do we have to tell which record to edit. Because when i try to edit the 2nd or 3rd record it always goes and updates the 1st record in the DB. – Sharon Watinsan Jan 09 '13 at 08:46
  • @sharonHwk This line `myEntites.Friend.SingleOrDefault(f => f.Id == id);` is picking the item you want to edit. `.SaveChanges()` will persist EVERYTHING that has changed. – Paul Fleming Jan 09 '13 at 09:59
  • Thank you i sorted the update issue. But i am still having trouble with Delete. when i click on delete i am taken to another page, where it will display the records that i chosed to delete and will ask if i want to delete the said record. In this page the record i want to delete is not shown therefore i get an error. Any idea how i could solve this ? I have updated my code above. – Sharon Watinsan Jan 09 '13 at 17:27
  • @sharonHwk Add a `@Html.HiddenFor(m => m.Id)`. Have your delete action take `int id`. – Paul Fleming Jan 09 '13 at 17:38
  • @sharonHwk Anywhere inside your form in your view. – Paul Fleming Jan 09 '13 at 17:48
1

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();
        }
RGR
  • 1,521
  • 2
  • 22
  • 36
  • What is `ObjectStateManager ` and `EntityState ` ? – Sharon Watinsan Jan 09 '13 at 08:58
  • Am i suppose to add some reference here ? – Sharon Watinsan Jan 09 '13 at 09:04
  • The 'ObjectStateManager' is to change the state from Added to Modified once the entity has been added to the context. 'EntityState' is the state of an entity object. Check this [link](http://stackoverflow.com/questions/623672/update-entity-framework-objects) also. – RGR Jan 09 '13 at 09:05
0

Just Proove of Concept Controler.UpdateModel wont work corectly.

Full Class here https://stackoverflow.com/a/39452785/1071165

const string PK = "Id";
protected Models.Entities con;
protected System.Data.Entity.DbSet<T> model;

[HttpPost]
public virtual ActionResult AddEdit(T item)
{
    TestUpdate(item);

    con.SaveChanges();

    return RedirectToAction("Index");
}

[HttpGet]
public virtual ActionResult Remove(string id)
{
    int nId = 0;
    int.TryParse(id, out nId);
    if (nId != 0)
    {
        var item = model.Find(nId);
        con.Entry(item).State = System.Data.Entity.EntityState.Deleted;
        con.SaveChanges();
    }
    return Redirect(Request.UrlReferrer.ToString());
}

private void TestUpdate(object item)
{
    var props = item.GetType().GetProperties();
    foreach (var prop in props)
    {
        object value = prop.GetValue(item);
        if (prop.PropertyType.IsInterface && value != null)
        {
            foreach (var iItem in (System.Collections.IEnumerable)value)
            {
                TestUpdate(iItem);
            }
        }
    }

    int id = (int)item.GetType().GetProperty(PK).GetValue(item);
    if (id == 0)
    {
        con.Entry(item).State = System.Data.Entity.EntityState.Added;
    }
    else
    {
        con.Entry(item).State = System.Data.Entity.EntityState.Modified;
    }

}
Community
  • 1
  • 1
Mertuarez
  • 901
  • 7
  • 24
0

Update:First Way

        public void IsActiveItem(int id)
         {
            var data = db.IRAS_InventoryItems.Find(id);
            data.IsActive = false;
            db.Entry(data).State = EntityState.Modified;           
            db.SaveChanges();
         }

Update: Second method

           public void IsActiveItem(int id)
           {
            var data = (from a in db.IRAS_InventoryItems
            where a.Id == id
            select a).FirstOrDefault();
            data.IsActive = false;
            db.Entry(data).State = EntityState.Modified;           
            db.SaveChanges();
           }

To Remove:first

         public void Remove(int id)
         {
            var data = db.IRAS_InventoryItems.Find(id);
            data.IsActive = false;
            db.IRAS_InventoryItems.Remove(data);       
            db.SaveChanges();
         }

To Remove: Second

              public void Remove(int id)
              {
                  var data = (from a in db.IRAS_InventoryItems
                  where a.Id == id
                  select a).FirstOrDefault();                      
                  db.IRAS_InventoryItems.Remove(data);          
                  db.SaveChanges();
               }
sapana
  • 46
  • 6
0

In Index Page(link for delete and Edit)

<td>
            <%: Html.ActionLink("Edit","Edit", new{StuID=@item.StudId}) %>
        </td>
        <td>
            <%: Html.ActionLink("Delete","Delete", new{StuID=@item.StudId}) %>
         </td>

Edit(First edit function is for edit page,it take all data of specific Id and second function is for saving the changes.)

 public ActionResult Edit(Int32 StuID)
    {
        var studata = stu.Studs.Where(x => x.StudId == StuID).FirstOrDefault();
        if (studata != null)
        {
            TempData["ID"] = StuID;
            TempData.Keep();
            return View(studata);
        }
        return View();
    }
    [HttpPost]
    public ActionResult Edit(Stud stu1)
    {
        Int32 StuID = (int)TempData["ID"];
        var studata = stu.Studs.Where(x => x.StudId == StuID).FirstOrDefault();
        studata.StudName = stu1.StudName;
        studata.StudAddress = stu1.StudAddress;
        studata.StudEmail = stu1.StudEmail;
        stu.ObjectStateManager.ChangeObjectState(studata,);
        stu.SaveChanges();
        return RedirectToAction("Index");
    }

Delete

public ActionResult Delete(int StuID)
    {
        if (StuID > 0)
        {
            var studata = stu.Studs.Where(x => x.StudId == StuID).FirstOrDefault();
            if (studata != null)
            {
                stu.DeleteObject(studata);
                stu.SaveChanges();
            }
        }
        return RedirectToAction("Index");
    }