2012-08-11 16 views
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(中)' 不能轉換爲 'System.Collections.Generic.List(中Laundry.BillView)'

這裏是我的條例草案和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 
+0

聽起來好像你需要在你的'Select'子句中構造一個新的'BillView'對象,而不是僅僅將字段選擇到這樣的匿名對象中。 (雖然我不完全知道VB的語法) – David 2012-08-11 21:27:09

+0

正如你所看到的,BillView只是我定義的模型,因爲我無法確定如何通過LINQ創建的聯合表發送給我的視圖。 – NickP 2012-08-11 21:28:42

+0

這是有道理的,但肯定它不能只是選擇一個BillView對象,如果一塊數據來自比爾模型和其他客戶模型? – NickP 2012-08-11 21:30:53

回答

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