简体   繁体   中英

How to write a LINQ Query to keep the most recent 10 entries

I have a table that I wish to only keep the most recent 10 records. If I were to write the query targeting MySQL, it would look something like the following:

DELETE FROM tblQuickLink 
WHERE ID NOT IN 
    (SELECT ID from tblQuickLink 
      ORDER BY EntryDate DESC 
      Limit 10)

I would like to construct a Linq query that would give me a collection of records which I would then use to remove from the target table by iterating thru the list and issuing a dbContext.Delete . I'm new to Linq and Entity Framework so if there's an easier way to achieve this then I'm all ears.

Thanks a bunch.

-- Val

I am not EF expert, not even beginner, but maybe this will work:

context.RemoveRange(context.tblQuickLink.OrderByDescending(x => x.EntryDate).Skip(10));
context.SaveChanges();

Query just retrieves data, so it cannot delete anything. You need to use RemoveRange method.

LINQ never changes the original input sequence!

You can only extract data from your input sequence. You can materialize this data and kindly ask the DbSet of your DbContext to delete these elements.

using (var dbContext = new MyDbContext(...))
{
    // get all but the 10 newest records
    var rowsToDelete = dbContext.QuickLinks
        .OrderByDescending(quickLink => quickLink.EntryDate)
        .Skip(10)
        .ToList();

    dbContext.QuickLinks.RemoveRange(rowsToDelete);
    dbContext.SaveChanges();
}

In words: MyDbContext contains a table of QuickLinks. Every Row in this table has a property EntryDate. Order the rows in the table of QuickLinks by descending value of EntryDate. The result is a sequence of rows with the newest EntryDate first. Skip the first 10 elements of this sequence, and put the rest in a list.

Ask the QuickLinks to remove all elements that are in the resulting list, and save the changes.

Simple comme bonjour!

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