var studentRepo = new StudentRepository();
int gradeParaleloId = Convert.ToInt32(cmbGradeParalelo.SelectedValue);
var students = studentRepo.FindAllStudentsFromGradeParalelo(gradeParaleloId);
int year = DateTime.Now.Year;
int month = Convert.ToInt32(cmbMes.SelectedIndex) + 1;
AttendanceRepository attendanceRepo = new AttendanceRepository();
for (int i = 0; i < students.Count; i++)
{
for (int j = 1; j < dataGridView1.Columns.Count; j++)
{
DateTime date = new DateTime(year, month, j);
var student = students[i];
var attendance = attendanceRepo.FindAttendance(student.StudentId, date);
if (attendance == null)
{
attendance = new Data.Repositories.Attendance();
attendanceRepo.Add(attendance);
}
attendance.StudentId = student.StudentId;
attendance.DateOfAttendance = date;
attendance.Attended = dataGridView1[j, i].Value.ToString();
}
}
attendanceRepo.SaveChanges();
My main thorn in the side is that for each day in the month, I have to query the database, and see if a record already exists in the DB for that day and student.
The upside is that I'm putting each attendance in the datacontext and only pushing the save at the very end as a transaction of sorts.
So I'm not inserting on every day for every student. Imagine for a class of 40 students. That's an easy \$40 * 30 = 1200\$ queries on the spot.
Is there some way for me to streamline this? I'm more concerned about this line:
var attendance = attendanceRepo.FindAttendance(student.StudentId, date);