簡體   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