2

I have an app where students can sign up for school courses. To prepare for their attendance information, I need data in the Attendance table to be populated. I would typically accomplish this task like this:

Attendance newAttendace = new Attendance
{
    CourseID = course.CourseID,
    StudentID = thisStudent.StudentID,
    AttendanceDay = 1,
    Present = false
};
db.Attendance.Add(newAttendance);
db.SaveChanges();

But I need to do this for every possible attendance day that the course has - so if there are 20 days that students will attend this course, I need to be able to add rows where AttendanceDay = 1 through 20.

I am thinking of doing this within a for loop and increasing Attendanceday 1 over and over and adding "newAttendance" to the database all 20 times then doing the db.SaveChanges() call - but I've never done a for loop while entering database entries before - is there a more elegant way of doing this within ASP.NET MVC with C#?

Massimo Fazzolari
  • 5,185
  • 3
  • 27
  • 36
Ecnalyr
  • 5,792
  • 5
  • 43
  • 89
  • How come you need an entry for each of the days upfront? When the student attends, can't you add an entry at that point? – Jamie Dixon Apr 26 '12 at 12:16
  • In my planning of the design I have come to the conclusion that this is the better way of doing things. I could be wrong. Was discussing this here: http://stackoverflow.com/questions/10317018/how-would-i-appropriately-design-a-viewmodel-to-edit-attendance-for-different-co – Ecnalyr Apr 26 '12 at 12:54

1 Answers1

3

I think that is the right way of doing it. But make sure your db.SaveChanges() is outside the loop. You need to call that only once

for(int i=0;i<20;i++)
{
   Attendance newAttendace = new Attendance
  {
    CourseID = course.CourseID,
    StudentID = thisStudent.StudentID,
    AttendanceDay = 1,
    Present = false
  };
  db.Attendance.Add(newAttendance);
}
db.SaveChanges();
Shyju
  • 214,206
  • 104
  • 411
  • 497