簡體   English   中英

Web API中的部分更新無效

[英]Partial update in Web API is not working

我在我的Web API中創建了一個post方法來對一個表進行部分更新 - 以更改表中的Order Status字段。 這是我到目前為止所得到的:

 public IHttpActionResult UpdateOrderStatus(Order ord)
 {
     try
     {
         if (!ModelState.IsValid)
         {
             throw new ProcessException("One or more values are invalid, please check.");
         }
         using (MyContext ctx = new MyContext())
         {
             ord.StatusID = 3;
             ctx.SaveChanges();

             return CreatedAtRoute("DefaultApi", new { id = ord.OrderID }, ord);
         }
     }
     catch (Exception ex)
     {
         throw new ProcessException(ex.Message);

     }
}

我正在逐步完成代碼,一切似乎都在工作 - 沒有錯誤,但數據庫沒有得到更新。 我究竟做錯了什么?

更新:

在將對象傳遞給Web API方法之前,在對象中設置StatusID:

var ord = {“OrderID”:1,“OrderDate”:CurrentDate,“StatusID”:3};

public IHttpActionResult UpdateOrderStatus(Order ord)
{
   try
   {
       if (!ModelState.IsValid)
       {
           throw new ProcessException("One or more values are invalid, please check.");
       }
       using (MyContext ctx = new MyContext())
       {
           ctx.Entry(ord).State = EntityState.Modified;
           ctx.SaveChanges();

         return CreatedAtRoute("DefaultApi", new { id = ord.OrderID }, ord);
       }
   }
   catch (Exception ex)
   {
       throw new ProcessException(ex.Message);

   }
}

如果您正在使用EntityFramework,那么您需要通知上下文您正在更新的Order對象。 DbSet您通常在名為Orders的上下文中具有DbSet屬性,因此我建議在設置StatusID之前添加ctx.Orders.Attach(Order)

嘗試此代碼:通過與ord.OrderID進行比較,從數據庫中獲取orderEntity,然后更新該記錄的StatusID。

using (MyContext ctx = new MyContext())
       {
           var orderEntity = ctx.Order.FirstOrDefault(x=> x.OrderID == ord.OrderID);
            orderEntity.StatusID = 3;
             ctx.SaveChanges();

         return CreatedAtRoute("DefaultApi", new { id = ord.OrderID }, ord);
       }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM