Csharp/C#教程:使用EF4时添加或更新相关实体集合的最佳策略?分享


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

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

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

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

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

上述就是C#学习教程:使用EF4时添加或更新相关实体集合的最佳策略?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

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

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/961700.html

(0)
上一篇 2021年11月26日
下一篇 2021年11月26日

精彩推荐