Reputation: 745
I've been running through the ASP.Net MVC C# Movie Database tutorial, but been trying to make a few minor changes to help learn what bits do what. I will add that I am a total beginner.
I have a page with a small form and a button, when I fill out the form and click submit the data in the form updates a pre-determined record in the database table.
In the controller code how do I specify a individual record? Assuming the table will only ever have one record in it, which is going to get updated periodically with new information?
I guess it is something to do with these two lines in the code:
db.Entry(data).State = EntityState.Modified;
db.SaveChanges();
I'm just not sure how to specify the record individually so it gets updated? The record will have an ID number (for example the ID will be "1").
The bit of code that will do the updating as it stands:
// POST: /Data/Update/
[HttpPost]
public ActionResult Update(Data data)
{
if (ModelState.IsValid)
{
db.Entry(data).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(data);
}
Upvotes: 1
Views: 2387
Reputation: 1462
EF need to know which row to update in the database. If the "ID" property wasn't bound from request, you need to set it explicitly in your code:
if (ModelState.IsValid)
{
data.Id = 1; //EF need to know which row to update in the database.
db.Entry(data).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
Upvotes: 1