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)?
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.
How about:
var lastN = MyDbContext.MyDbSet
.OrderByDescending(g => g.Id)
.Take(N);
MyDbContext.MyDbSet.RemoveRange(lastN);