我有一个继承数据库模型的ViewModel。我无法弄清楚如何从数据库中填充ViewModel。
“视图模型”
Public Class CustomerView
Inherits Customer
Private lookUp As New LookUpData
ReadOnly Property OwnerList As List(Of SelectListItem)
Get
Return lookUp.OwnersList(True)
End Get
End Property
End Class
“控制器”
Function Edit(Optional Id As Integer = Nothing) As ActionResult
Dim model As New CustomerView
model = (From c In db.Customers Where c.Id = Id AndAlso c.OrganisationId = s.OrganisationId).FirstOrDefault
If model Is Nothing Then
Return RedirectToAction("List")
Else
Return View(model)
End If
End Function
我收到了无效的强制转换异常。
非常感谢任何帮助。
答案 0 :(得分:0)
您的Linq查询返回(我假设)作为您需要投影到视图模型对象中的Customer
对象的列表。通过添加select
:
model = (From c In db.Customers _
Where c.Id = Id AndAlso _
c.OrganisationId = s.OrganisationId _
Select New CustomerView With { _
.CompanyName = c.CompanyName, _
.Address = c.Address, _
.City = cust.City, _
.Country = cust.Country}).FirstOrDefault
自从我做VB之后已经有一段时间了,但这应该可以工作或只需要调整。