Marius Vasile

Marius Vasile

  • 552
  • 1.9k
  • 145.9k

asp.net core Add data in table for an array of dates

Feb 3 2023 4:50 PM

I have the following problem, I get an array of dates with

DateList = new List<DateTime>();
DateTime startTime = DateTime.Now.AddYears(1);

var firstDayOfMonth = new DateTime(startTime.Year, startTime.Month, 1);
var lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddTicks(-1);
var lastDayOfMonthCMP = firstDayOfMonth.AddDays(22);

var daysInPeriod = (lastDayOfMonthCMP - firstDayOfMonth).Days;

var daysInMonth = DateTime.DaysInMonth(startTime.Year, startTime.Month);
var dates = Enumerable.Range(1, daysInPeriod)
                      .Select(s => new DateTime(startTime.Year, startTime.Month, s))
                      .Where(date => date.DayOfWeek != DayOfWeek.Friday)
                      .Where(date => date.DayOfWeek != DayOfWeek.Saturday)
                      .Where(date => date.DayOfWeek != DayOfWeek.Sunday)
                      .Where(date => date.DayOfWeek != DayOfWeek.Monday)
                      .ToArray();

Now, I want to insert data in a table for each day in array but only 5 entries for each date. When count reach 5 it should pass to next date. I tried with:

foreach(var date in DateList)
{

    var newData = new ProgCMP()
    {
        UCMP = ucmp,
        TipCMP = "Test CMP",
        ProgDate = date
    };
    var count = await _context.ProgCMPs.Where(s => s.ProgDate == newData.ProgDate).CountAsync();
    if (count < 5)
    {
        if (await TryUpdateModelAsync(newData, "ProgCMP"))
        {
            _context.ProgCMPs.Add(newData);
            await _context.SaveChangesAsync();
            return RedirectToPage("/CMP/Index");
        }
    }
}

but is not working. what should be the approach?


Answers (2)