代码之家  ›  专栏  ›  技术社区  ›  JoseMarmolejos

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

  •  0
  • JoseMarmolejos  · 技术社区  · 14 年前

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

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

    1 回复  |  直到 10 年前
        1
  •  1
  •   andyp    14 年前

    您可以遍历学生的数据库集合,删除所有不在updatedStudentsCollection中的学生,并添加所有在updated集合中但不在数据库集合中的学生。但如果这真的不那么奇怪的话…-)

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