我需要在HttpPost Edit方法中获取特定字段“Quantity”的数据库值,以便我可以对其执行某些操作,然后更新其值。我正在使用实体框架6.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> EditGoogles([Bind(Include = "ProductID,Name,Code,Quantity,etc)] SalesDetail salesdetail)
{
if (ModelState.IsValid)
{
var oldValue = db.Entry(salesdetail).GetDatabaseValues();
//here i want to get the Quantity from database
int QtyBefore = ???;
db.Entry(salesdetail).State = EntityState.Modified;
salesdetail.Quantity = //do some operaion with QtyBefore Here and update
await db.SaveChangesAsync();
return Json(new { success = true });
}
return PartialView("_EditSales", salesdetail);
}
答案 0 :(得分:0)
你可以这样做:
if (ModelState.IsValid)
{
Models.YourTableName oldValue = db.YourTableName.Where(q=>q.Quantity==salesdetail.Quantity).Select(p=>p).SingleOrDefault();
oldValue.Quantity= YourNewValue;
...
答案 1 :(得分:0)
如果没有真正掌握所有必要信息,我认为您需要的是:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> EditGoogles([Bind(Include = "ProductID,Name,Code,Quantity,etc)] SalesDetail salesdetail)
{
if (ModelState.IsValid)
{
var oldValue = db.Entry(salesdetail).GetDatabaseValues();
//here i want to get the Quantity from database
int QtyBefore = db.Set<SalesDetail>().FirstOrDefault(x => x.Quantity == yourquantityid)?.Quantity ;
db.Entry(salesdetail).State = EntityState.Modified;
salesdetail.Quantity = //do some operaion with QtyBefore Here and update
await db.SaveChangesAsync();
return Json(new { success = true });
}
return PartialView("_EditSales", salesdetail);
}
您还可以找到大量关于查询数据库的文章,例如this一个。