Marius Vasile

Marius Vasile

  • 590
  • 1.9k
  • 148.6k

Use EF Core to add each day from date range

Jan 23 2023 9:07 AM

I am trying to add all days from a date range in my database but I couldn't find a way to do that

I am getting the data range from View with

<form method="post">
    <div class="row no-gutters">
        <div class="col-sm-2">
            <label class="form-control labelSecondary">Data de inceput</label>
            <input name="sdate" class="form-control spanSecondary" type="date" />
        </div>
        <div class="col-sm-2">
            <label class="form-control labelSecondary">Data de sfarsit</label>
            <input name="edate" class="form-control spanSecondary" type="date" />
        </div>
    </div>
    <div class="row no-gutters mt-2 mb-4">
        <div class="col-sm-2 text-left">
            <button id="btnSubmit" class="btn-link col-sm-12 btnSubmit" type="submit" asp-page-handler="AddNew">
                Salveaza
            </button>
        </div>
    </div>
</form>

but to add I could only test for one value

public async Task<IActionResult> OnPostAddNewAsync(DateTime sdate, DateTime edate)
{
    var newData = new CMPAvDate()
    {
        CMPDate = sdate
    };

    if (await TryUpdateModelAsync(newData, "CMPAvDate"))
    {
        _context.CMPAvDates.Add(newData);
        await _context.SaveChangesAsync();
        return RedirectToPage("/CMP/CMPSchedule", new {sdate});
    }

    return RedirectToPage("/CMP/CMPSchedule");
}

I also tried without success

public static IEnumerable<DateTime> EachCalendarDay(DateTime sdate, DateTime edate)
{
    for (var date = sdate.Date; date.Date <= edate.Date; date = date.AddDays(1)) yield
    return date;
}

foreach (DateTime day in EachCalendarDay(sdate, edate))
{
    var newData = new CMPAvDate()
    {
        CMPDate= day
    };
    if (await TryUpdateModelAsync(newData, "CMPAvDate"))
    {
        _context.CMPAvDates.Add(newData);
        await _context.SaveChangesAsync();
        return RedirectToPage("/CMP/CMPSchedule");
    }
}

 


Answers (4)