使用EF4时添加或更新相关实体集合的最佳策略?

假设您有一个带有Student实体集合的Classroom实体。 我通常在创建一个新学生时需要将它添加到课堂中的是使用Classroom.Students.Add(newStudent),现在当我想要更新这个集合时,我通常会清除()该集合并再次添加学生,喜欢:

theClassroom.Students.Clear(); foreach(Student student in updatedStudentsCollection) { theClassroom.Students.Add(student); } 

清除集合并再次添加实体感觉有点古怪,所以我想应该有一个更好的策略来实现这个场景。 请分享你通常如何处理这个问题。

您可以迭代学生的数据库集合,并删除所有不在updatedStudentsCollection中的学生,并添加更新集合中但不在数据库集合中的所有学生。 但如果那真的不那么古怪.. 😉

 theClassroom.Students.Remove(x => !updatedStudentsCollection.Contains(x)); foreach (var student in updatedStudentsCollection) if (!theClassroom.Students.Contains(student)) theClassroom.Students.Add(student);