如何在删除多个记录中最小化C#,LINQ代码

时间:2019-05-06 12:22:06

标签: c# linq entity-framework-core

这是从库存表中删除零库存记录的方法。我想减少LINQ在数据库上执行的代码/次数。

库存表

public class Inventory
    {
        public int itemCode { get; set; }
        public decimal price { get; set; }
        public decimal availQty { get; set; } // Can have Negative values.
    }

示例数据

itemCode    price       availQty
1           10           10
1           12          -10
2           10           10

从上面的记录中,我要删除itemCode == 1的所有记录,因为net availQty为0。

这是我的方法

private void RemoveZeroInvs()
        {
        // Remove individual zero Inventorys
            var rinvs = from ri in _context.Inventorys
                        where ri.availQty == 0
                        select ri;

            _context.Inventorys.RemoveRange(rinvs);
            _context.SaveChanges();

            // Remove if group is zero in availQty, as it allows Negative Qty.
            var result = from d in _context.Inventorys
                         group d by new
                         {
                             d.itemCode
                         }
                          into g
                         select new
                         {
                             g.Key.itemCode,
                             availQty = g.Sum(y => y.availQty)
                         };

            var zrs = from r in result
                      where r.availQty == 0
                      select r;

            foreach (var zr in zrs) // Here, zrs length may be more than 500
            {
                var ri = _context.Inventorys.Where(w => w.itemCode == zr.itemCode);
                _context.Inventorys.RemoveRange(ri);
                _context.SaveChanges();
            }
        }

我使用Asp.Net Core 2.2。有这种可能性吗?

我在循环的_context.Inventorys.RemoveRange(ri);行也收到以下错误。

A command is already in progress: SELECT t."itemCode", t."availQty"
FROM (
    SELECT d."itemCode", SUM(d."availQty") AS "availQty"
    FROM "Inventorys" AS d
    GROUP BY d."itemCode"
) AS t

1 个答案:

答案 0 :(得分:0)

var todelete = _context.Inventorys
   .GroupBy(i => i.itemCode)
   .Where(g => g.Sum(i => i.availQty) == 0)
   .SelectMany(g => g);

就数据库执行而言,这是代码的较短版本,您必须比较原始查询。但是,您的代码可能会更轻松...