【问题标题】:Failed to update data into the database无法将数据更新到数据库中
【发布时间】:2021-04-07 16:04:51
【问题描述】:

我不明白为什么会发生此错误。我的程序是这样的:-我在数据库中收集了许多数据,并且还列出了会话数据的类型。其中“会话”数据 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
}

这是我的输出:

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

【问题讨论】:

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


    【解决方案1】:

    想想这里发生了什么:

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

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

    因此,您不想用t[i] 索引到t。您只希望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()。为什么不只在最后调用一次呢?

    【讨论】:

    • 实际上,进一步的整理是t.Quantity -= shop[i].Quantity;
    【解决方案2】:

    t是店铺的过滤列表,所以它的数量小于等于shop.Count,你不能使用i作为t的索引。

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

      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();
                }
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-19
      • 1970-01-01
      • 1970-01-01
      • 2014-06-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多