简体   繁体   中英

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.

Instead of add the element squadra to the list, you can update every single element of the object from the db like that:

//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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM