0

I have a table with name "Loggs" as you see in image.

enter image description here

I want to create action that delete all records that is older than two weeks. For example today is 2017-11-20 and LoggId 1 , 2 and 3 have old Loggdate. How to create to delete them? I tried to put those LoggId's in Array , and I tried even old dates in Array but then I don't know how to do ....

Here is Array of old dates

public DateTime[] OldDates()
{
  var oldDate = DateTime.Now.AddDays(-14);

 return  context.Loggs.Where(u => u.LoggDate < oldDate).Select(d => d.LoggDate).ToArray();

} 

And tried by Id's too

public int[] OldDateId()
{
  var oldDate = DateTime.Now.AddDays(-14);
  return  context.Loggs.Where(u => u.LoggDate < oldDate).Select(d => d.LoggId).ToArray();

}

But then How to create delete action....? I tried like this but I don't how to complite it

public ActionResult DeleteOldLogs()
{
  var datesToRemove = OldDates();
  using (context)
  {
    context.Loggs.Remove(.....) // I don't know how to formulate here ..;)
  }
}

Thank you in advance!

Helen Tekie
  • 515
  • 1
  • 6
  • 23
  • Possible duplicate of [How do I delete multiple rows in Entity Framework (without foreach)](https://stackoverflow.com/questions/2519866/how-do-i-delete-multiple-rows-in-entity-framework-without-foreach) – Igor Nov 20 '17 at 19:24

3 Answers3

4

You can use the RemoveRange method which accepts a collection of your entities.

Also your action method needs to return something.

public ActionResult DeleteOldLogs()
{
    var oldDate = DateTime.Now.AddDays(-14);
    var oldItems = context.Loggs.Where(u => u.LoggDate < oldDate);
    context.Loggs.RemoveRange(oldItems);
    context.SaveChanges();

    return Content("Deleted successfully");
}

When this code gets executed, EF will issue one SELECT query to get the older records and execute N number of DELETE queries where N is the number records returned from the first SELECT query.

Another option is to call Remove for each item in your oldItems collection

var oldItems = context.Loggs.Where(u => u.LoggDate < oldDate);
foreach (var oldItem in oldItems)
{
    context.Loggs.Remove(oldItem);
}
context.SaveChanges();

Keep in mind that you are calling the AddDays methods to the current time stamp. So if your table column has time stamp(DateTime), it will delete the records after that timestamp(not from 12.00 AM)

Shyju
  • 214,206
  • 104
  • 411
  • 497
2

I assume Loggs is a table and you're asking how to use Entity to delete something?

var oldDate = DateTime.Now.AddDays(-14);
var dates = context.Loggs.Where(l => l.LoggDate < oldDate);
context.Loggs.RemoveRange(dates);
context.SaveChanges();
Sean Sherman
  • 327
  • 1
  • 16
1
public ActionResult DeleteOldLogs()
{
  var datesToRemove = OldDates();
  using (context)
  { 
    foreach (var item in datesToRemove)
    {
        context.Loggs.Remove(item);
        context.SaveChanges();
    }
  }
}
Saqib A. Azhar
  • 994
  • 1
  • 15
  • 27