问题
here's my question: I have an MVC3 C# application and I need to update a value in a DbSet from the Edit controller, so the T item's value will be replaced with a new one. I don't want to delete the item and add it again. I cannot figure out how to do this. DbSet doesn't seem to have something like an index.
Here's my Edit controller:
public class ItemController : Controller
{
private SESOContext db = new SESOContext();
private FindQrs fqr = new FindQrs();
[HttpPost]
public ActionResult Edit(Item item)
{
if (ModelState.IsValid)
{
db.Entry(item).State = EntityState.Modified;
Qr qr = fqr.FindQr(item.QR);
// update somewhere here
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.SetID = new SelectList(db.Sets, "SetID", "Name", item.SetID);
return View(item);
}
}
EDIT: The above controller is for the Item entity which on Create action creates instances of the Qr entity. I just want to add something which on Edit action will update the Value field of the Qr entity with the value from the view (the Value field of Qr is supposed to be unique).
Where FindQrs method looks like this:
public class FindQrs
{
private SESOContext db = new SESOContext();
public Qr FindQr(string qr)
{
List<Qr> qrList = db.Qrs.ToList<Qr>();
Qr foundQr = qrList.Find(delegate(Qr qrDel) { return qrDel.Value == qr; });
return foundQr;
}
}
And Qr is a class which contains only an ID and a string Value fields. Qrs is the mentioned DbSet from the context. It looks like this:
public DbSet<Qr> Qrs { get; set; }
Any help will be appreciated.
回答1:
You are perhaps updating the value in a different DbContext. Try this:
[HttpPost]
public ActionResult Edit(Item item)
{
if (ModelState.IsValid)
{
db.Entry(item).State = EntityState.Modified;
Qr qr = fqr.FindQr(item.QR, db);
// update somewhere here
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.SetID = new SelectList(db.Sets, "SetID", "Name", item.SetID);
return View(item);
}
public class FindQrs
{
public Qr FindQr(string qr, SESOContext db) // pass in the db context
{
List<Qr> qrList = db.Qrs.ToList<Qr>();
Qr foundQr = qrList.Find(delegate(Qr qrDel) { return qrDel.Value == qr; });
return foundQr;
}
}
来源:https://stackoverflow.com/questions/9788445/updating-dbsett-items-value-from-the-controller-c-mvc-code-first