我正在嘗試獲取gridview的數據併發生轉換錯誤。在Linq查詢中拋出錯誤
在下面的代碼中,如果我只是返回「myuserlist」 - 一切都很好。只要我嘗試選擇只有2個字段(如在此代碼中),我得到了鑄件錯誤。我已經看過在這裏發佈的關於這個問題的其他評論,並嘗試了一些沒有成功的事情。
Imports System.Linq
Imports RoutesEntities
Partial Class ProfileTest
Inherits System.Web.UI.Page
Private myentity As New RoutesEntities()
Public Function GridView1_GetData() As IQueryable(Of AllUser)
Return From myuserlist In myentity.AllUsers Select New With {myuserlist.UserName,myuserlist.Email}
End Function
錯誤:
System.InvalidCastException was unhandled by user code
HResult=-2147467262
Message=Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[VB$AnonymousType_0`2[System.String,System.String]]' to type 'System.Linq.IQueryable`1[AllUser]'.
Source=App_Web_oelfrca5
StackTrace:
at ProfileTest.GridView1_GetData() in C:\xxx\yyy\zzz\Profile.aspx.vb:line 10
InnerException:
我想這(除其他事項外):
Return From myuserlist In myentity.AllUsers Select New AllUser() With {
.UserName = myuserlist.UserName,
.Email = myuserlist.Email}
,並得到這個:
Exception Details: System.NotSupportedException: The entity or complex type 'RoutesModel.AllUser' cannot be constructed in a LINQ to Entities query.
雖然它是一個C#的帖子(和一個很好的答案),這也適用於VB.NET:http://stackoverflow.com/questions/5325797/the-entity-cannot-be-constructed-in-a -linq-to-entities-query – Styxxy