[英]How can I update database records?
I have code like this: 我有这样的代码:
[HttpPost]
public static bool AggiornaInstallatore(FormCollection form)
{
using (var ctx = new termostore_installazione_Entities())
{
var idr = Convert.ToInt32(form["id_installatore"]);
var installatore = ctx.installatori.Where(x => x.Id == idr).FirstOrDefault();
var squad = Convert.ToInt16(form["squadra"]);
var squadra = ctx.squadra.Where(x => x.id == squad).FirstOrDefault();
if (form["edit_nome"] != "") { installatore.nome = form["edit_nome"]; }
if (form["edit_cognome"] != "") { installatore.cognome = form["edit_cognome"]; }
if (form["edit_email"] != "") { installatore.mail = form["edit_email"]; }
if (form["edit_telefono"] != "") { installatore.telefono = form["edit_telefono"]; }
if (form["edit_indirizzo"] != "") { installatore.indirizzo = form["edit_indirizzo"]; }
if (form["edit_zona_competenza"] != "") { installatore.zona_competenza = form["edit_zona_competenza"]; }
installatore.squadra.Add(squadra);
ctx.SaveChanges();
}
return true;
}
Now, instead of adding squadra
I want to update this record, but I don't know how to do it. 现在,我不想更新
squadra
,而是要更新此记录,但是我不知道该怎么做。
Instead of add the element squadra
to the list, you can update every single element of the object from the db like that: 无需将
squadra
元素添加到列表中,您可以像这样从db更新对象的每个元素:
//The element you already have in your example
var squadra = ctx.squadra.Where(x => x.id == squad).FirstOrDefault();
squadra.name = form.name; //I assume you get te updated value from form
squadra.type = form.type;
...
ctx.SaveChanges();
You have the squad element updated and, with the SaveChanges
method, the updates are set even on the db. 您已更新了小队元素,并使用
SaveChanges
方法甚至在数据库上也设置了更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.