linq to entities加入表而不将结果转换为视图

时间:2014-02-14 18:53:26

标签: asp.net-mvc-4 linq-to-entities

我想将我加入的lINQ表达式中的两个表的所有列都发送到我的视图中。 它基本上是客户记录以及客户地址记录。它在VB中,但C#答案会很好。

我不确定我的方法是否正确,并且无法将结果转换为视图所期望的结果。

我的结果类定义为

Partial Public Class CustomerContext
    Private m_customer As List(Of Customer)
    Public Property cust As List(Of Customer)
        Get
            cust = m_customer
        End Get
        Set(value As List(Of Customer))
            m_customer = value
        End Set
    End Property

    Private m_address As List(Of CustomerAddress)
    Public Property addr As List(Of CustomerAddress)
        Get
            addr = m_address
        End Get
        Set(value As List(Of CustomerAddress))
            m_address = value
        End Set
    End Property

End Class

我的控制器定义如下:         函数详细信息(可选ByVal id As Integer = Nothing)As ActionResult

        Dim cc = (From c In db.Customers Join a In db.CustomerAddresses On c.CustomerID Equals a.AddressID
        Where (c.CustomerID = id)
        Select New CustomerContext With {.addr = db.CustomerAddresses.ToList, .cust = db.Customers.ToList})

        If IsNothing(cc) Then
            Return HttpNotFound()
        End If

        Return View(cc)

    End Function

我的观点是

@Modeltype MvCAdventureWorkTest.CustomerContext

<table>
<tr class="displayline">
<td>
    <table>
        <tr>
            <td>
                @Html.DisplayNameFor(Function(model) model.cust.Item("Name"))
            </td>
            <td class="displaydatahalf">
                @Html.DisplayFor(Function(model) model.cust.item("Name"))
            </td>
        </tr>

       <tr>
            <td >
                @Html.DisplayNameFor(Function(model) model.addr.item("address"))
            </td>
            <td>
                @Html.DisplayFor(Function(model) model.addr.item("address"))
            </td>
        </tr>

我收到的错误消息是

传递到字典中的模型项的类型为'System.Data.Objects.ObjectQuery`1 [MvCAdventureWorkTest.CustomerContext]',但此字典需要类型为“MvCAdventureWorkTest.CustomerContext”的模型项。

1 个答案:

答案 0 :(得分:0)

我已经得出结论,你不能或不能轻易地将一个类型为iqueryable的对象传递给可用类型,无论是ienumerable还是list(of),但是工作如下:

Dim cc As New CustomerContext cc.cust =(from c in db.Customers Where(c.CustomerID = id)选择c).ToList cc.addr =(来自in db.CustomerAddresses Where(a.CustomerID = id)选择a).ToList()

返回视图(cc)