简体   繁体   中英

How do I go about updating all relative records with my linq instead of first or default?

In order to update my records with my checkout link I passed the query string unum through an Html.ActionLink , then call it in my ActionResult .

public ActionResult Checkout(Order order, int ? unum)
{            
    order = db.Orders.FirstOrDefault(o => unum == o.OrderNum);
    order.RecievedShirt = false;
    order.OrderCompleted = true;
    db.SaveChanges();

    var AuthenticationManager = HttpContext.GetOwinContext().Authentication;
    AuthenticationManager.SignOut();
    return RedirectToAction("Purchased", "Orders");        
}

While this works it only updates the first record. How do I update them all?

The FirstOrDefault method returns the first element matching the where condition. If you want all records matching the condition,Use Where method to get all orders matching that unum (assuming you have more than one orders matching OrderNum value with unum variable value) and udpate the property values inside a loop.

Also there is no need of the Order parameter in the action method as you are getting orders matching your where condition.

public ActionResult Checkout(int? unum)
{            
    if(unum!=null)
    {
      var allOrders = db.Orders.Where(o =>  o.OrderNum==unum.Value);
      foreach(var order in allOrders)
      {
         order.RecievedShirt = false;
         order.OrderCompleted = true;
      }
      db.SaveChanges();
    }
    //to do : Do something if unum is null ????? 
    var AuthenticationManager = HttpContext.GetOwinContext().Authentication;
    AuthenticationManager.SignOut();
    return RedirectToAction("Purchased", "Orders");        
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM