簡體   English   中英

實體框架 SaveChanges() 不起作用?

[英]Entity Framework SaveChanges() is not working?

當我調用SaveChanges()時,實體框架不會保存我的更改。

這是我的代碼:

Model

Partial Public Class Doctor
    Public Property DoctorID As Integer
    ...

    Public Overridable Property Patients As ICollection(Of Patient) = New HashSet(Of Patient)

End Class

視圖模型

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 代碼段有問題。 為了說明問題,我每次執行編輯時都會清除患者列表。

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

我希望清除患者列表,並從DoctorPatient中刪除記錄。 但是,這些更改不會“采取”。

關於如何調試或修復的任何建議?

截圖:

  • 在編輯期間,我從醫生那里清除患者名單
  • 保存記錄后DoctorPatient記錄並沒有被刪除,頁面上仍然存在醫生和患者對象的關系

我從來不知道清除集合以從數據庫中刪除實體。 我希望它更像:

For Each p as Patient In Doctor.Patients
    db.Patients.Remove(p)
Next p

db.SaveChanges()

順便說一句,將 db 實體放入視圖模型並不是真正的設計意圖。 db 實體傾向於作為在中間層和 db 之間穿梭數據的設備,視圖模型用於在中間層和 UI 之間穿梭數據。 中間層執行從一個到另一個的映射

這是解決我的問題的代碼更改。 我不知道為什么它起作用了。

感謝提供答案的 SO 用戶 Stritof。

Function Edit(ByVal doctorViewModel As DoctorViewModel) As ActionResult

    If ModelState.IsValid Then

        Dim item = db.Entry(Of Doctor)(doctorViewModel.Doctor) '<-- this was it
        item.State = EntityState.Modified
        item.Collection(Function(i) i.Patients).Load()

        item.Entity.Patients.Clear()

        db.Entry(doctorViewModel.Doctor).State = EntityState.Modified

        db.SaveChanges()

        Return RedirectToAction("Index")

    End If

    Return View(doctorViewModel)

End Function

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM