如何在[HttpPost]编辑方法中获取特定字段的数据库值?

时间:2016-07-30 07:43:41

标签: c# asp.net asp.net-mvc entity-framework

我需要在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);
}

2 个答案:

答案 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一个。