简体   繁体   中英

How to delete 1000 records based upon created date ascending using Entity Framework?

I have a requirement to delete last 1000 records from a table based upon created date and then insert new 1000 records from a different table.

What would be the best possible way to do it?

public void mymethod()
{
     // TestBasketRequests (delete thousands records from here)
     // Call Delete();
}

public void Delete(IList<TestBasketRequest> TestBasketRequests)
{
    using (var dbContext = new myContext())
    {
        dbContext.Entry(TestBasketRequests).State = EntityState.Deleted;
        dbContext.SaveChanges();
    }
}

The

RemoveRange()

method is used to delete multiple items from the database. And in the method you have to use to get the last 1000 items using

TakeLast() 

will only return last items based on the order they were added to the database.

Inside your mymethod() u have to write something like this

var lastN = MyDbContext.MyDbSet
                   .OrderByDescending(g => g.CreateDate)
                   .Take(1000);

MyDbContext.MyDbSet.RemoveRange(lastN);

I didnt test this code.you can make changes as per your requirements.

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