0

我真的很难让我加入的两个表在视图中显示(我只想显示来自客户表的客户名称和来自账单表的账单状态 - 这两个表都在 CustomerId 主键上)。我花了很长时间研究这个并得出结论,为这个视图创建另一个模型,但是当我尝试使用以下内容时,我在我的控制器中做了:

Function ShowAll() As ViewResult
    Dim BillQuery = From d In db.Bills
                    Join c In db.Customers On d.CustomerId Equals c.CustomerId
                    Select c.CustSurname, d.BillStatus

    Dim BillList As List(Of BillView) = BillQuery.ToList()

    Return View(BillList)
End Function

我收到一个错误:

'System.Collections.Generic.List(Of )' 类型的值无法转换为 'System.Collections.Generic.List(Of Laundry.BillView)'

这是我的 Bill 和 BillView 模型:

Imports System.Data.Entity
Imports System.ComponentModel.DataAnnotations

Public Class Bill

    'Key
    Public Property BillId() As Integer

    'Others
    <Required()>
    <Display(Name:="Customer ID")>
    Public Property CustomerId() As String

    <Required()>
    <Display(Name:="Bill Status")>
    Public Property BillStatus() As String

End Class

Public Class BillView

    Public Property CustSurname() As String

    Public Property BillStatus() As String

End Class

和客户模型:

Imports System.Data.Entity
Imports System.ComponentModel.DataAnnotations

Public Class Customer

'Key
Public Property CustomerId() As Integer

'Others
<Display(Name:="Group ID")>
Public Property GroupId() As Integer

<Required()>
<Display(Name:="Firstname")>
Public Property CustFirstname() As String

<Required()>
<Display(Name:="Surname")>
Public Property CustSurname() As String

<Display(Name:="Email")>
Public Property CustEmail() As String

<Display(Name:="Cellphone")>
Public Property CustCellphone() As String

<Display(Name:="Address")>
Public Property CustAddress() As String

<Required()>
<Display(Name:="Status")>
Public Property CustStatus() As String

<Required()>
<Display(Name:="Account Balance")>
Public Property AccBalance() As Double

<Required()>
<Display(Name:="Loyalty Ammount")>
Public Property LoyaltyAmount() As Double

<Required()>
<Display(Name:="Customer Discount")>
Public Property PersonalDiscount() As Double


End Class
4

1 回答 1

2

看起来您的第一个 LINQ 查询正在返回一个匿名类型,该类型随后无法转换为List(Of BillView). 尝试使用以下代码在强制转换BillView之前返回模型集合(注意添加的语法Select New BillView With {})。

Function ShowAll() As ViewResult
    Dim BillQuery = From d In db.Bills
                    Join c In db.Customers On d.CustomerId Equals c.CustomerId
                    Select New BillView With {.CustSurname = c.CustSurname, .BillStatus =  d.BillStatus}

    Dim BillList As List(Of BillView) = BillQuery.ToList()

    Return View(BillList)
End Function
于 2012-08-11T22:20:10.497 回答