I am really struggling with getting two tables I have joined to show in a view (I just want to show the customer name which comes from the customer tables and the bill status from the bill table – both of which are joint on a CustomerId primary key). I spent ages researching this and came to the conclusion of creating another model just for this view which I did however in my controller when I try and use the following:
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
I get an error:
Value of type ‘System.Collections.Generic.List(Of )’ cannot be converted to ‘System.Collections.Generic.List(Of Laundry.BillView)’
Here are my Bill and BillView models:
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
And Customer Model:
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
It looks like your first LINQ query is returning an anonymous type which can’t then be cast to
List(Of BillView). Try the following code to return a collection ofBillViewmodels prior to the cast (note the added syntaxSelect New BillView With {}).