根据日期自动更改值

Changing values automatically based on date

我有这个对象

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

它存储如下值:

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

这里我设置 Iteration active 如果它在范围内,这是在创建一个新的迭代时(POST 请求)。

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);
}

现在问题出在字段 Active 上,我在创建新迭代时检查了它。但是我希望它不仅在创建时随时自动更改,我该怎么做?例如,日期更改并且有一个更改活动迭代的新检查。

我认为您在这里需要的是一种保持 运行 并不时检查迭代的服务。

例如,您可以创建一个 windows 服务,每 24 小时验证一次迭代,如果它已过期,则将其取消激活。无论如何,您都必须创建一个更新方法。

检查此 link 以获得帮助: https://stackify.com/creating-net-core-windows-services/

我认为您使更新数据库条目的事情变得复杂,因为您始终可以从 startend 属性计算该值。

如果你需要在后端访问它,你可以只在你的模型上创建扩展

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

或者在将其发送给客户端之前将其映射到 ViewModel:

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; } 
    }
}