4

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)?

Community
  • 1
  • 1
Bad
  • 4,967
  • 4
  • 34
  • 50
  • EF Provides `Remove` what to Remove is with respect to the requirement. I think , The `TakeLast` will iterate through database to get last element , this is in efficient if you have large number of data. Skipping all the previous data is not sound good to me. Ty something `TakeLast` where you get `DbSet.LastOrDefault` and Remove the item – Eldho May 14 '16 at 14:00
  • @Eldho: In my case I want to remove not only last element, but last elements (several of them). – Bad May 14 '16 at 14:09
  • `RemoveRange` is okay but how do you get the last elements – Eldho May 14 '16 at 14:10

2 Answers2

1

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.

Amit Hasan
  • 1,430
  • 1
  • 15
  • 33
1

How about:

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

MyDbContext.MyDbSet.RemoveRange(lastN);
aligray
  • 2,812
  • 4
  • 26
  • 35