0

Entity Framework delete a number of records

using (Galway__Entities db = new Galway__Entities())
{
    DateTime RemovableDate = new DateTime();

    List<PROJ_ACCS_StockControl_DeletedPLURecord> DeletedPLURecords = db.PROJ_ACCS_StockControl_DeletedPLURecord.Where(x => x.TimeStamp <= RemovableDate).ToList();

    db.??????
    //so I delete the list all at once or use a foreach and run round each record?
    //how do I delete each singular record if this is the case then.
}
Craig W.
  • 17,838
  • 6
  • 49
  • 82
John
  • 3,965
  • 21
  • 77
  • 163
  • 2
    If you are using EF6, check [this question](http://stackoverflow.com/questions/21568479/how-can-i-delete-1-000-rows-with-ef6). There is suggested to use `RemoveRange` method. – alexmac Mar 27 '14 at 11:23

3 Answers3

2

You could use:

DeletedPLURecords.ForEach(element => db.PROJ_ACCS_StockControl_DeletedPLURecord.Remove(element));
db.SaveChanges();
neel shah
  • 2,231
  • 15
  • 19
1

Try this:

 using (Galway__Entities db = new Galway__Entities())
    {
      DateTime RemovableDate = new DateTime();
      List<PROJ_ACCS_StockControl_DeletedPLURecord> DeletedPLURecords = db.PROJ_ACCS_StockControl_DeletedPLURecord.Where(x => x.TimeStamp <= RemovableDate).ToList();

      foreach (var item in DeletedPLURecords)
      {
          var e = db.PROJ_ACCS_StockControl_DeletedPLURecord.Find(item.Id);
          if (e != null)
          {
               Db.PROJ_ACCS_StockControl_DeletedPLURecord.Remove(e);
          }
      }
      db.SaveChanges();
    }
Jeyhun Rahimov
  • 3,769
  • 6
  • 47
  • 90
0

currently to remove multiple records you need to first get records in memory then remove them. another solution is that you can use EntityFramework.Extended library to make this a single request process. like

....
db.PROJ_ACCS_StockControl_DeletedPLURecord.Where(x => x.TimeStamp <= RemovableDate).Delete();
mohsen dorparasti
  • 8,107
  • 7
  • 41
  • 61