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,617
  • 4
  • 32
  • 49
  • 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

3 Answers3

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,310
  • 1
  • 14
  • 32
1

How about:

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

MyDbContext.MyDbSet.RemoveRange(lastN);
aligray
  • 2,804
  • 4
  • 24
  • 35
0

I would suggest something like this

var lastUser = MyDbContext.Users.Select(g => g.Id).Max();

This will get the user with maximum id and delete the user. This is workaround i dont know is there any simple work around for this. I believe this is more effective than query depicted in your question. Still you get only item Instead of a list

But will only get the last item

MyDbContext.Users.Remove(lastUser);
MyDbContext.SaveChanges();
Eldho
  • 7,344
  • 3
  • 41
  • 72