ASP.NET MVC:无法转换ObjectQuery - > Linq.IQueryable

时间:2009-10-22 12:17:15

标签: asp.net-mvc entity-framework

我必须做错事,或者我不明白。我正在尝试使用来自我的实体框架的数据来填充“PropAllMenus”(具有一堆属性)。但是,当通过函数进行转换时,我在'WeekMenuRepository'中得到'InvaldCastExeption'。这是代码:

PropAllMenus

Public Class PropAllMenus

    Private _MenuID As Integer
    Public Property MenuID() As Integer
        Get
            Return _MenuID
        End Get
        Set(ByVal value As Integer)
            _MenuID = value
        End Set
    End Property

    Private _Name As String
    Public Property Name() As String
        Get
            Return _Name
        End Get
        Set(ByVal value As String)
            _Name = value
        End Set
    End Property

    Private _DaypartID As Integer
    Public Property DaypartID() As Integer
        Get
            Return _DaypartID
        End Get
        Set(ByVal value As Integer)
            _DaypartID = value
        End Set
    End Property

End Class

WeekMenuRepository

Private _db As New EDMWeekmenuEntities()
    Public Function ListAllMenus() As IQueryable(Of PropAllMenus) Implements IWeekMenuRepository.ListAllMenus
        Dim result = From p In _db.Menus _
                     Select p
        Return result

    End Function

的HomeController

Dim DoThings As New WeekMenuRepository()
     Function Index() As ActionResult

            Return View(DoThings.ListAllMenus().ToList)

End Function

1 个答案:

答案 0 :(得分:2)

PropAllMenus不是实体类型,因此EF无法将类似Menu的实体类型隐式转换为它。

换句话说,您的函数结果类型为IQueryable(Of PropAllMenus),但您的查询返回ObjectQuery(Of Menu)之类的内容。如果您可以将查询更改为返回ObjectQuery(Of PropAllMenus),那么隐式转换(当您调用Return时)将返回IQueryable。

您需要执行以下操作:

    Dim result = From p In _db.Menus _
                 Select New PropAllMenus With
                 {
                     .MenuId = p.MenuId,
                     .Name = p.Name,
                     // etc.
                 }

顺便说一下,我注意到你问了6个问题,但从未接受过任何答案,也没有上传任何内容。您应该按下您认为有用的任何答案旁边的“向上箭头”,然后按下您最常帮助的答案旁边的“复选标记”图标。这是一种说“谢谢你”的方式。