When I call SaveChanges()
, Entity Framework is not saving my changes.
Here's my code:
Model
Partial Public Class Doctor
Public Property DoctorID As Integer
...
Public Overridable Property Patients As ICollection(Of Patient) = New HashSet(Of Patient)
End Class
Viewmodel
Public Class DoctorViewModel
Public Property Doctor As Doctor
Public Property AllPatients As IEnumerable(Of SelectListItem)
Private Property _selectedPatients As List(Of Integer)
Public Property pSelectedPatients As List(Of Integer)
...
End Property
End Class
Controller snippet with the problem. To illustrate the problem I'm clearing the list of patients every time an edit is performed.
Function Edit(ByVal doctorViewModel As DoctorViewModel) As ActionResult
If ModelState.IsValid Then
doctorViewModel.Doctor.Patients.Clear()
db.Entry(doctorViewModel.Doctor).State = EntityState.Modified
db.SaveChanges()
Return RedirectToAction("Index")
End If
Return View(doctorViewModel)
End Function
I would expect the list of patients to be cleared, and records to be deleted from DoctorPatient
. However these changes don't "take".
Any suggestions on how to debug or fix?
Screenshots:
- During Edit I clear the list of patients from the doctor
- After saving the record, the
DoctorPatient
records have not been deleted, and the relationship between doctor and patient objects is still on the page