所以我有一个函数,可以从 Web 服务获取学生列表,并在 localdb 中查询其中所有学生。 数据放置在两个不同的列表中。所以我想检查一下本地数据库列表中是否已经存在新学生。如果是,请更新它,如果没有,则添加它。我无法让它工作.我正在尝试使用 LINQ 执行此操作,但我似乎无法使其正常工作。我的 LINQ 技能充其量是业余的。
public async Task GetStudents()
{
String controllerName = "Students";
List<Students> newStudentData = await RunGetAsync<Students>(controllerName);
// get all the service types that already exists in the localStudent Db
List<Students> currentStudentData = db.Studentss.ToList();
foreach (Students existingStudents in currentStudentData)
{
foreach (Students newStudents in newStudentData)
{
IEnumerable<Students> selectStudents = from student in newStudentData // check if Students exist in the database
where student.Id == existingStudents.Id
select student;
if (selectStudents == null) // didn't find it, then add it
{
db.Students.Add(newStudents);
}
if (selectStudents != null) // found it , then update the informations
{
Students updatedStudents = new Students();
foreach (var field in selectStudents)
{
updatedStudents.FName = field.FName;
updatedStudents.LName = field.LName;
updatedStudents.ZipCode = field.ZipCode;
updatedStudents.AccessCode = field.AccessCode;
}
db.Entry(updatedStudents).State = System.Data.Entity.EntityState.Modified;
}
}
}
db.SaveChanges();
}
非常感谢您的帮助。
你循环的次数比你需要的多:
foreach (Students newStudents in newStudentData)
{
var student = currentStudentData.FirstOrDefault(s => s.Id == newStudents.Id);
if(student == null)
{
//add
}
else
{
//update
}
}
使用FirstOrDefault
,您可以找出它是否存在,并同时获取对它的引用(如果存在)。
您可以使用
Intersect 和 Except 如下所示:
//Find students that already exist to update
var updateStudents = currentStudentData.Intersect(newStudentData);
//Find new students to add
var addStudents = newStudentData.Except(currentStudentData);