简体   繁体   中英

How do I update specific records using a comparison with linq?

I am trying to update records in my Orders table where the query string is equal to the customer order or OrderNum in the table. This is what I have tried:

public ActionResult Checkout(Order order)
{
    string newNum = Request.Params["unum"];
    int mynum = 0;
    bool res = int.TryParse(newNum, out mynum);

    //order = db.Orders.Single(o => mynum == o.OrderNum); - tried this first
    order = db.Orders.Single(o => o.OrderNum == mynum);
    order.RecievedShirt = false;
    order.OrderCompleted = true;
    db.SaveChanges();

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

The error that returns is Sequence contains no elements

Edited

I was able to resolve this specific issue by doing the following. Action Link on checkout button in cart:

@Html.ActionLink("Checkout", "Checkout", new { unum = ViewBag.Data}, htmlAttributes: new { @class = "checkout-btn" })

Then I made the following updates to the action:

public ActionResult Checkout(Order order, int ? unum)

Then I changed the linq to reflect:

order = db.Orders.FirstOrDefault(o => unum == o.OrderNum);

However, because this only updates the first record instead of all I cannot mark it as the answer, but wanted to mark it as progress as it did resolve the question I asked...somewhat

Probably you are doing something wrong and the Order is not saved in the db. Sequence contains no elements means that your Query returned nothing, so please check if it's inserted correctly first (using the SQL Server Data Explorer is an easy way).

Also, as OrderNum is the primary key in your table, try using Find(key) (which is also faster than the Single ) instead, like this:

order = db.Orders.Find(mynum);

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