2012-08-11 59 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