1

In a daily import procedure processed in an MVC application, I need to delete all entities that have a datestamp in a fixed timehorizon before doing the actual import. Is there a way to bring this code..

var deleteShows = db.Shows.Where(x => x.begin >= DateTime.Today.Date).ToList();
foreach (Show show in deleteShows)
    {
        db.Shows.Remove(show);
    }
db.SaveChanges();

.. into a shorter / quicker version, something like

db.Shows.Where(x => x.begin >= DateTime.Today.Date).ToList().ForEach(db.Shows.Remove(???));
peter
  • 2,103
  • 7
  • 25
  • 51
  • 2
    https://github.com/loresoft/EntityFramework.Extended/wiki/Batch-Update-and-Delete – ta.speot.is Aug 21 '13 at 08:12
  • Although not a duplicate, this question has an overview of all mass-delete options available in EF: http://stackoverflow.com/questions/2519866/how-do-i-delete-multiple-rows-in-entity-framework-without-foreach – CodingIntrigue Aug 21 '13 at 09:05

1 Answers1

2

Yeah indeed:

db.Shows.Where(x => x.Date >= DateTime.Today.Date)
    .ToList().ForEach( s => db.Shows.Remove(s));
Amin Saqi
  • 18,549
  • 7
  • 50
  • 70
  • Thank you, that works and looks much better :o) one correction (my fault): in the Where-part, delete ".Date" from x-selection: db.Shows.Where(x => x.begin >= DateTime.Today.Date) .ToList().ForEach( s => db.Shows.Remove(s)); – peter Aug 21 '13 at 09:08
  • Isn't `s => db.Shows.Remove(s)` redundant and can simply be `db.Shows.Remove`? – ta.speot.is Aug 21 '13 at 09:12
  • @ta.speot.is - I don't think so. Because the `.Remove(T entity)` gets an entity object and hasn't any overload for taking no arguments... – Amin Saqi Aug 21 '13 at 09:17
  • @AminSaghi ta.speot.is was talking about a method-group – TGlatzer Aug 21 '13 at 09:18
  • @Grumbler85 - I don't know about that. What is method-group? – Amin Saqi Aug 21 '13 at 09:23
  • To continue @Grumbler85's comment: http://stackoverflow.com/a/2914951/242520 is the best example – ta.speot.is Aug 21 '13 at 10:28