繁体   English   中英

如何使用 Entity Framework Core 3.1 在一个事务中删除不超过 X 行

[英]How to delete no more than X rows in one transaction using Entity Framework Core 3.1

由于性能因素,我必须使用单个事务删除不超过一定数量的行。 应首先删除与我的 where 子句匹配的前 x 个元素。 然后重复该操作,直到受影响的行数不返回0。然后完成整个过程。 如何使用 Entity Framework Core 3.1 编写这样的逻辑?

首先,您可以从数据库中查询数据库,然后使用 While 循环或 DO/While 循环来检查已删除的项目计数并循环遍历已删除的项目,然后再删除项目。 代码如下:

        //query database and get the deleted items.
        //test data.
        List<category> itemlist = new List<category> ();
        for(int i =1; i<=100; i++)
        {
            itemlist.Add(new category() { ID = i, Name="name "+i });
        }
        var index = 0;

        while (itemlist.Count > 0)
        {
            //create transaction and remove items 
            foreach (var item in itemlist.OrderBy(c=>c.ID).Take(5))
            {
                Console.WriteLine("Remove item " + item.Name);
                itemlist.Remove(item);
            }
            index++;
            Console.WriteLine("Count " + index);
        } 

暂无
暂无

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

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