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,250
  • 6
  • 47
  • 81
John
  • 3,853
  • 20
  • 69
  • 146
  • 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,121
  • 14
  • 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,711
  • 6
  • 44
  • 88
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
  • 7,342
  • 5
  • 38
  • 59