【问题标题】:How do I implement a ViewModel in this controller? MVC, EntityFramework如何在此控制器中实现 ViewModel? MVC,实体框架
【发布时间】:2020-06-25 12:54:52
【问题描述】:

数据库优先设计。我想在我的 Doctor Edit page 上实现一个 DoctorViewModel,这样我就可以编辑医生和他的病人之间的关系。

问题是未保存对所选患者列表的更改。

控制器代码:

Function Edit(ByVal doctor As Doctor) As ActionResult
    If ModelState.IsValid Then

        db.Entry(doctor).State = EntityState.Modified
        db.SaveChanges()
        Return RedirectToAction("Index")

    End If

    Return View(doctor)

End Function

视图模型:

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)
        Get
            If _selectedPatients Is Nothing Then
                _selectedPatients = Doctor.Patients.[Select](Function(m) m.PatientID).ToList()
            End If

            Return _selectedPatients
        End Get
        Set(value As List(Of Integer))
            _selectedPatients = value
        End Set
    End Property

End Class

医生模型:

Partial Public Class Doctor
    Public Property DoctorID As Integer
    Public Property Name As String
    Public Property Description As String
    Public Property DateCreated As Nullable(Of Date)
    Public Property CreatedBy As String
    Public Property IsDeleted As Nullable(Of Boolean)

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

End Class

截图:

  1. Index page 正确显示医生及其患者。

  2. Edit page 显示所有可用的患者并突出显示选定的患者。可以在此处保存对医生属性的更改,但忽略对患者选择的任何更改。没有错误。

【问题讨论】:

    标签: vb.net entity-framework viewmodel


    【解决方案1】:

    这就是解决方案。

    我仍然不确定它为什么起作用,即。为什么对医生字段(姓名、描述等)的更改会保存,但对患者子列表的更改不会。

    Function Edit(ByVal doctorViewModel As DoctorViewModel) As ActionResult
    
        If ModelState.IsValid Then
    
            'Grab the Doctor record and his associated patient records
            Dim item = db.Entry(Of Doctor)(doctorViewModel.Doctor)
            item.State = EntityState.Modified
            item.Collection(Function(i) i.Patients).Load()
    
            'Create new list of selected patients
            Dim pPatients As New List(Of Patient)
            For Each i In doctorViewModel.pSelectedPatients
                pPatients.Add(db.Patients.Find(i))
            Next
    
            'Replace entity's patients with the new list of patients
            item.Entity.Patients = pPatients
    
            'Save
            db.Entry(doctorViewModel.Doctor).State = EntityState.Modified
            db.SaveChanges()
    
            Return RedirectToAction("Index")
    
        End If
    
        Return View(doctorViewModel)
    
    End Function
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多