I am using foreach loop to insert Values to database. I Have two students in Class Six and six subjects for same class. When I run it, it upload only one subject for all students, i want to populate all subjects w.r.t students of class six... Where do I need iterarion in my code?
var source = context.Students.Include("ClassRoom").Where(x => x.ClassRoom.ClassName == searchLookUpEdit4.Text).ToList();
Evaluation ev = new Evaluation();
var source1 = context.Subjects.Include("ClassRoom").Where(x => x.ClassRoom.ClassName == searchLookUpEdit4.Text).ToList();
foreach (var stud in source)
{
ev.StudentId = stud.Id;
foreach (var sub in source1)
{
ev.SubjectId = sub.Id;
}
ev.TermId = Convert.ToInt32(searchLookUpEdit2.EditValue);
ev.ObtainedMarks = 0;
ev.Grades = "";
ev.Remarks = "";
context.Evaluations.Add(ev);
context.SaveChanges();
}
I think you inner foreach
loop is not written correctly. Correcting the braces position will fix this issue.
Corrected Code:
var source = context.Students.Include("ClassRoom").Where(x =>
x.ClassRoom.ClassName == searchLookUpEdit4.Text).ToList();
Evaluation ev = new Evaluation();
var source1 = context.Subjects.Include("ClassRoom").Where(x => x.ClassRoom.ClassName == searchLookUpEdit4.Text).ToList();
foreach (var stud in source)
{
ev.StudentId = stud.Id;
foreach (var sub in source1)
{
ev.SubjectId = sub.Id;
ev.TermId = Convert.ToInt32(searchLookUpEdit2.EditValue);
ev.ObtainedMarks = 0;
ev.Grades = "";
ev.Remarks = "";
context.Evaluations.Add(ev);
context.SaveChanges();
}
}
I assume you meant that you want one evaluation per combination of students and subjects. In that case you should do just that:
foreach (var stud in source)
{
foreach (var sub in source1)
{
var ev = new Evaluation();
ev.StudentId = stud.Id;
ev.SubjectId = sub.Id;
ev.TermId = Convert.ToInt32(searchLookUpEdit2.EditValue);
ev.ObtainedMarks = 0;
ev.Grades = "";
ev.Remarks = "";
context.Evaluations.Add(ev);
context.SaveChanges();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.