简体   繁体   中英

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

Due to performance factor i have to delete no more than a certain amount of rows using a single transaction. The first x elements matching my where clause should be deleted first. Then the operation should repeat until the affected rows count will not return 0. Then the whole process is completed. How to write such a logic using Entity Framework Core 3.1?

First, you could query the database from the database, then, use the While loop or DO/While loop to check the deleted item count and loop through the deleted items, after that delete items. code like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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