C# - MVC application How to update and delete a record from the database

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>

Delete

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

Update

Friend f = myEntities.Friend.FirstOrDefault(x => x.Id = MyId);
f.Name = NewName;
myEntities.SaveChanges();

Provide CRUD (Create, Read, Update, Delete) Data Form Entry , NerdDinner Step 5: Create, Update, Delete Form Scenarios NET MVC 3, we recommend you follow the Getting Started With MVC Dinner data in our DinnerRepository (and from there to the database). When we run the application and request the "/Dinners/Edit/1" URL we will see the following page:. Here Employee information will be used as primary data. Employee name, Designation, Department can be added into SQL database table and Updated or deleted using the MVC View. Hence implementing our CRUD functionality of MVC. A single C# method in MVC controller will be used to perform all three actions (CRUD) in web application.


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.

Tutorial: Update related data with EF in an ASP.NET MVC app , To delete a record from database, again we will be using. This is because we can't keep the same name of the action method with same parameter in C#. This is step 5 of a free "NerdDinner" application tutorial that walks-through how to build a small, but complete, web application using ASP.NET MVC 1. Step 5 shows how to take our DinnersController class further by enable support for editing, creating and deleting Dinners with it as well.


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

Delete record from database in ASP.NET MVC, Net MVC applications instead of using DataSet, Command, of this AuthorId we will Edit the record and update the record in the database. Deleting Database Records in ASP.NET MVC Application. In this article, I am going to discuss Deleting Database Records in ASP.NET MVC Application. Please read our previous article before proceeding to this article where we discussed Model Binding using Interface in ASP.NET MVC Application.


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;
    }

}

Select Insert, Update And Delete With ASP.NET MVC, Creating Insert Update and Delete Application In MVC 4 Using Razor After getting the ID, get data from the database depending on that id  In this Article, we will learn How to Insert, Update and Delete Record in DataGridView in C# Windows Form Application. In Previous Post, we saw How to Create a simple Windows Form Login Application in C#. Create a new Windows Form Application. Create a Database (named as Sample). Add a Table tbl_Record. The following is the table schema for


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

Creating Insert Update and Delete Application In MVC 4 , asp.net MVC application with create update delete and view operations. the sample Duration: 20:01 Posted: Mar 8, 2017 You now have a complete ASP.NET MVC application that stores data in a local DB database. You can create, read, update, delete, and search for movies. Next Steps. After you have built and tested a web application, the next step is to make it available to other people to use over the Internet. To do that, you have to deploy it to a web hosting provider.


Asp.net Mvc : Create Update Delete View With Entity Framework , Full CRUD: insert update delete view data from sql database in ASP.NET MVC Framework Duration: 4:44 Posted: Mar 5, 2017 The department name in the Index page list comes from the navigation property, showing that the relationship was established correctly. Run the Edit page (display the Course Index page and click Edit on a course). Change data on the page and click Save. The Course Index page is displayed with the updated course data.


ASP.NET MVC #15 : Insert Update Delete and View data from , Delete myEntities.Friend.Remove(f); myEntities.SaveChanges();. Update Friend f = myEntities.Friend.FirstOrDefault(x => x.Id = MyId); f. Clicking on Delete button calls DeleteConfirmed action method. Notice the attribute ActionName that instruct the ASP.NET MVC framework that despite the name of the method is DeleteConfirmed, it’s name should be treated as Delete. This is because we can’t keep the same name of the action method with same parameter in C#. This is a trick to


Deleting Database Records in ASP.NET MVC, In this article, I try to explain Deleting Database Records in ASP.NET MVC application step by step with a simple example using both Get and Post Requests​. Select C# as the programming language and select the ASP.NET MVC Web Application project template. Give your project the name MovieApp and click the OK button. Figure 01 : The New Project dialog box ( Click to view full-size image )