C# - MVC 应用程序如何更新和删除数据库中的记录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14230851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# - MVC application How to update and delete a record from the database
提问by sharon Hwk
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>
回答by Paul Fleming
To update, it's the same as add but without the .Friend.Add(f)
. Load the item like so:
要更新,它与添加相同,但没有.Friend.Add(f)
. 像这样加载项目:
var friendEntity = myEntites.Friend.SingleOrDefault(f => f.Id == id);
friendEntity.Field1 = f.Field1;
...
myEntities.SaveChanges();
To delete, use the opposite of .Add(f)
, .Remove
.
要删除,使用的对面.Add(f)
,.Remove
。
回答by Alexandr Sulimov
Delete
删除
myEntities.Friend.Remove(f);
myEntities.SaveChanges();
Update
更新
Friend f = myEntities.Friend.FirstOrDefault(x => x.Id = MyId);
f.Name = NewName;
myEntities.SaveChanges();
回答by RGR
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();
}
回答by Mertuarez
Just Proove of ConceptControler.UpdateModel wont work corectly.
只是概念的证明Controler.UpdateModel 无法正常工作。
Full Class here https://stackoverflow.com/a/39452785/1071165
完整课程在这里 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;
}
}
回答by sapana
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();
}
回答by Hitanshi Mehta
In Index Page(link for delete and Edit)
在索引页面(删除和编辑链接)
<td>
<%: Html.ActionLink("Edit","Edit", new{[email protected]}) %>
</td>
<td>
<%: Html.ActionLink("Delete","Delete", new{[email protected]}) %>
</td>
Edit(First edit function is for edit page,it take all data of specific Id and second function is for saving the changes.)
编辑(第一个编辑功能用于编辑页面,它获取特定 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");
}
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");
}