Delete last N records, Entity Framework

c# entity-framework entity-framework-6

Question

I use the following code to remove last N records in Entity Framework:

Extension method to take last N elements, taken from here:

public static IEnumerable<T> TakeLast<T>(this IEnumerable<T> source, int N)
{
    return source.Skip(Math.Max(0, source.Count() - N));
}

Remove last N elements:

MyDbContext.MyDbSet.RemoveRange(MyDbContext.MyDbSet.TakeLast(N));

Is it effective? I do not want to reinvent the wheel. Maybe I missed some existing function like collection.RemoveLast (although I couldn't find one with my first effort)?

1
4
5/23/2017 11:58:42 AM

Accepted Answer

The method you have is ok. The RemoveRange() method is used to delete multiple items from the database. And the method you are using to get the last n items is okay as well. However TakeLast() will only return last items based on the order they were added to the database.

1
5/14/2016 2:40:20 PM

Popular Answer

How about:

var lastN = MyDbContext.MyDbSet
                       .OrderByDescending(g => g.Id)
                       .Take(N);

MyDbContext.MyDbSet.RemoveRange(lastN);


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow