簡體   English   中英

C#-MVC應用程序如何更新和刪除數據庫中的記錄

[英]C# - MVC application How to update and delete a record from 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; }
    }
}

-

控制器

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

要將記錄添加到數據庫,我使用了以下代碼。 有效;

myEntities.Friend.Add(f);
myEntities.SaveChanges();
return RedirectToAction("Index");

更新

<%@ 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>

刪除

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

更新資料

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

要進行更新,它與add相同,但是沒有.Friend.Add(f) 像這樣加載項目:

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

要刪除,請使用.Add(f).Remove的反義詞。

更新:

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

刪除:

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

只是Concept Controler.UpdateModel的證明無法正常工作。

完整課程在這里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;
    }

}

更新:第一方法

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

更新:第二種方法

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

刪除:首先

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

刪除:第二

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

在索引頁面中(用於刪除和編輯的鏈接)

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

編輯(第一個編輯功能用於編輯頁面,它獲取特定ID的所有數據,第二個功能用於保存更改。)

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

刪除

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM