kr_v
kr_v

Reputation: 139

Changing values automatically based on date

I have this object

public class Iteration
{
    public int Id { get; set; }
    public DateTime Start { get; set; }
    public DateTime End { get; set; }
    public bool Active { get; set; }
}

And it stores values like:

Id: 1
Start 10-07-2019
End 17-07-2019
Active: true

Here I set Iteration active if it is in the range, this is when creating a new iteration (POST request).

public async Task<ActionResult> AddIteration([FromBody]IterationDTO iterationDTO)
{
    // Set active if current date is in the added range
    if (DateTime.Now.Date >= iterationDTO.Start.Date && DateTime.Now.Date <= iterationDTO.End.Date)
    {
        iterationDTO.Active = true;
    }
    DB.Set<Iteration>().Add(iterationDTO);
    await DB.SaveChangesAsync();
    return Ok(iterationDTO);
}

Now the problem is with the field Active, I check it when creating a new iteration. But I want it to change automatically any time not just when creating, how can I do this? For example, day changes and there is a new check that changes the active iteration.

Upvotes: 0

Views: 1179

Answers (2)

zhuber
zhuber

Reputation: 5524

I think that you are complicating things with updating database entry since you can always compute that value from start and end properties.

You can just create extension on your model if you need to access it on backend

public static class IterationExtensions {
    public static bool Active(this Iteration iteration)
    {
        return DateTime.Now.Date >= iteration.Start.Date && DateTime.Now.Date <= iteration.End.Date;
    }
}

or just map it to ViewModel before sending it to client:

public class IterationViewModel
{
    public int Id { get; set; }
    public DateTime Start { get; set; }
    public DateTime End { get; set; }
    public bool Active 
    { 
        get { return DateTime.Now.Date >= this.Start.Date && DateTime.Now.Date <= this.End.Date; } 
    }
}

Upvotes: 3

mvoelcker
mvoelcker

Reputation: 348

I think that what you need here is a service that keep running and checking the iteration from time to time.

You could, for example, create a windows service that, for every 24 hours, validate the iteration and, if it is out of date, unactivate it. You will have to create a update method anyways.

Check this link for help: https://stackify.com/creating-net-core-windows-services/

Upvotes: 0

Related Questions