简体   繁体   English

如何通过与linq进行比较来更新特定记录?

[英]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. 我正在尝试更新我的Orders表中的查询字符串等于表中的客户订单或OrderNum的记录。 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 返回的错误是Sequence不包含任何元素

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: 然后我更改了linq以反映:

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). Sequence contains no elements意味着您的查询未返回任何内容,因此请先检查是否正确插入了该语句(使用SQL Server Data Explorer是一种简便方法)。

Also, as OrderNum is the primary key in your table, try using Find(key) (which is also faster than the Single ) instead, like this: 另外,由于OrderNum是表中的主键,因此请尝试使用Find(key) (它也比Single更快),如下所示:

order = db.Orders.Find(mynum);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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