First of all, I assume that you know that the class already exists in the database. The easiest approach is to request it first. The reason you really get the newly entered ClassRoom entry is because you are using ctx.AddToClassRooms(classRoomEntry) . This binds the object to the context and sets the EntityState to Added .
private void UpdateClassRoom(ClassRoomDto classRoomDto) { using (var ctx = new TrainingContext()) { ClassRoom classRoomEntity = ctx. ClassRooms. Include("Students"). Single(c => c.ClassID == classRoomDto.ClassId); classRoomEntity.ClassName = classRoomDto.ClassName; foreach (var studentDto in classRoomDto.Students) { if (studentDto.StudentId == 0) {
To remove a student from the 3D class, you just need to remove him from the collection (but DO NOT FIND the ctx.DeleteObject() call, as this will remove the student from the database. Your example, the above code will not take care of this, since it only adds new ones students: Instead of matching all students who are in the database but not in your DTO, you can use a simpler approach: first clear the list and then add students:
private void UpdateClassRoom(ClassRoomDto classRoomDto) { using (var ctx = new TrainingContext()) { ClassRoom classRoomEntity = ctx. ClassRooms. Include("Students"). Single(c => c.ClassID == classRoomDto.ClassId); classRoomEntity.ClassName = classRoomDto.ClassName; classRoomEntity.Students.Clear(); foreach (var studentDto in classRoomDto.Students) { Student student; if (studentDto.StudentId == 0) {
This is probably the approach you are looking for. I specially wrote the first piece of code to show you various cases of handling new and existing objects, but this is a more correct approach (simpler). Hope this helps.
Yakimych
source share