未能将数据更新到数据库中

时间:2020-12-31 09:30:50

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

我不明白为什么会发生这个错误。我的程序是这样的:-我将许多数据收集到数据库中,并且还列出了会话数据的类型。其中“会话”数据 ID 类似于我的数据库数据 ID,在那里我使用功能更改数量。但是当我循环的最后一次计数更改我的数量属性时(我调试了那个),然后我发现了这个错误。

这是我的代码:

public async Task<IActionResult> Checkout(Order11 anOrder)
{
    List<Shop> shop = HttpContext.Session.Get<List<Shop>>("shop");

    for (int i = 0; i < shop.Count; i++)
    {
        // var r = shop[i].Id;
        if (_db.Shop.Any(x => x.Id == shop[i].Id))
        {
            var t = _db.Shop.Where(x => x.Id == shop[i].Id).ToList();

            if (t[i].Quantity > 0)
            {
                t[i].Quantity = (t[i].Quantity - shop[i].Quantity) 
            }
               
            _db.SaveChanges();
        }
    }

    // other code
}

这是我的输出:

enter image description here

我不明白这个问题的解决方案是什么。我是初学者。请帮忙。

2 个答案:

答案 0 :(得分:2)

想想这里发生了什么:

var t = _db.Shop.Where(x => x.Id == shop[i].Id).ToList();

假设您的 ID 是唯一的,这将导致只有一个项目,但会将其作为列表的唯一成员返回。

因此您不想使用 t 索引到 t[i]。您只希望 t[0] 获得唯一的元素。

然而,整个事情可以变得更整洁:

for (int i = 0; i < shop.Count; i++)
{
     // Single() returns null for no match, the object for a single match
     // and throws an exception for multiple matches
     var t = _db.Shop.Single(x => x.Id == shop[i].Id);

     // ?. first checks if t is null, and only then looks at Quantity
     // if t is not null (i.e. Single() has returned a match)
     if (t?.Quantity > 0)
     {
         t.Quantity = (t.Quantity - shop[i].Quantity);

         _db.SaveChanges();
     }         
}

(单独的问题,但我不确定您是否需要在循环内调用 _db.SaveChanges()。为什么不只在最后调用一次?

答案 1 :(得分:1)

t 是筛选后的店铺列表,所以它的数量小于或等于shop.Count,你不能使用i作为t的索引。< /p>

您可以像下面那样更改您的代码。

  for (int i = 0; i < shop.Count; i++)
        {
            if (_db.Shop.Any(x => x.Id == shop[i].Id))
            {
                var t = _db.Shop.Where(x => x.Id == shop[i].Id).ToList();
                foreach (var x in t)
                {
                    if (x.Quantity > 0)
                    {
                        x.Quantity = (x.Quantity - shop[i].Quantity);
                    }
                }

                _db.SaveChanges();
            }
        }