views:

16

answers:

1

First table: School (Id, Name)
Second table: Student (Id, SchoolId, Name)

Suppose I have received updated roster for a school:

var school = db.Schools.Single(s => s.Id == updatedSchoolId);
school.Students = updatedStudents;
db.SubmitChanges();

This does not work, since disconnected students will end up with SchoolId set to null (orphants).

Question: what is a preferred way to update child collection?
or am I stuck with executing DeleteOnSubmit to get rid of orphans?

I would prefer a complete example.

At this time I compare both collections to produce 3 lists: removed items, added items, matched items. But I had to code this collection comparison, and it takes 12 lines of code, and it ain't pretty.

A: 
using (DataContext db = new DataContext())
{
    IEnumerable<Student> newRoster = updatedStudents;
    var school = db.Schools.Single(s => s.Id == updatedSchoolId);

    // First, handle deletions.
    var deletedStudents = newRoster.Select(n => !(school.Students.Select(s => s.Id).Contains(n.Id)));

    school.Students.DeleteAllOnSubmit(deletedStudents);

    // Next, handle adds and updates.
    foreach (Student student in newRoster)
    {
        if (school.Students.Select(s => s.ID).Contains(student.Id)
        {
            ... update the necessary fields ...
        }
        else
            school.Students.Add(student);
    }

    db.SubmitChanges();
}
Neil T.
Is there a way to do same without deleting students that haven't changed? Suppose I keep grades for each student.
This routine only deletes students appearing on the original roster that do not appear on the new roster.
Neil T.