2009-10-22 53 views
0

我必須做錯了什麼或者我不明白這一點。我試圖用來自我的實體框架的數據填充'PropAllMenus'(有一堆屬性)。但是,當通過函數進行轉換時,我在'WeekMenuRepository'中獲得了'InvaldCastExeption'。下面是代碼:ASP.NET MVC:無法轉換ObjectQuery - > Linq.IQueryable

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 

回答

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個問題,但從來沒有接受任何的答案,也沒有任何上傳。您應該按任何您認爲有幫助的答案旁邊的「向上箭頭」,然後按回答問題的單個最有用答案旁邊的「複選標記」圖標。這是一種說「謝謝」的方式。

+1

+1爲'順便說一句'段落。 – 2012-06-03 08:31:06

相關問題