-1

What I want to do is simple. If the DateTimeOffSet of a created Event is older than 24 hours I want it removed from the database. I am having a huge amount to trouble working with Converting System.Linq.IQueryable to System.DateTime.

Any help will be greatly appreciated. This is the Index of Events

public ActionResult Index()
{
    IQueryable<DateTimeOffset> b = db.Events.Select(x => x.EventTime);
    DateTimeOffset currentDate = DateTimeOffset.Now;
    if (currentDate > b)
    {
        db.Events.Remove(@event);
        db.SaveChanges();
        return View(db.Events.ToList());
    }

    return View(db.Events.ToList());
}

My other question is how could I structure this so that it requires a 24 hour difference in order to remove the row from database.

The data table has the EventTime as a DateTimeOffset data type.

I have also been trying to use

DateTimeOffset.Compare(currentDate, b);

But Visual Studio isn't liking that line as well. Please help if you know how to compare a time from a database to current time. There is really nothing like this in regards on this site. I Have spent all day on this site and have yet to find something along this.

Thanks

Fayyaz Naqvi
  • 695
  • 7
  • 19

2 Answers2

1

It might be easier to do the comparison in the query:

public ActionResult Index()
{
    DateTimeOffset currentDate = DateTimeOffset.Now.AddDays(-1);
    IQueryable<Event> events = db.Events.Where(x => currentDate > x.EventTime);

    foreach(var e in events){ 
    {
        db.Events.Remove(e);
    }
    db.SaveChanges()

    return View(db.Events.ToList());
}

You can then loop through and remove each one. I would also do save changes outside the loop so that we are committing changes once and not several times.

Dhunt
  • 1,584
  • 9
  • 22
0

You could do something like this

foreach (var a in b)
{
     if( (currentDate - a).Hours >= 24 ) 
    {
        ...
    }
}

See the example here: https://msdn.microsoft.com/en-us/library/bb352700(v=vs.110).aspx

currentDate - b would return a TimeSpan object, and you could use the Hours property on it to do the check.

See all TimeSpan members here: https://msdn.microsoft.com/en-us/library/system.timespan_members(v=vs.90).aspx

Fayyaz Naqvi
  • 695
  • 7
  • 19
  • Thanks for the response! Great Idea on getting the value to be >= 24. Yet I am still running into the same problem with this. – AtLeastTheresToast Oct 31 '15 at 04:33
  • Thanks for the response good idea on the >=24. yet I am still having the same problem. Operator '-' cannot be applied to operands to type 'DateTimeOffset' and 'IQueryable' – AtLeastTheresToast Oct 31 '15 at 04:37