Linq查询中的强制转换错误

时间:2013-11-24 19:55:09

标签: vb.net linq entity-framework

我正在尝试获取gridview的数据并出现转换错误。

在下面的代码中,如果我只返回“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.

1 个答案:

答案 0 :(得分:0)

如果您在编译时不需要特定的AllUser类型,则可以让您的函数返回IQueryable(Of Object),或者甚至是简单的IQueryable

Public Function GridView1_GetData() As IQueryable
    Return From myuserlist In myentity.AllUsers Select New With {myuserlist.UserName,myuserlist.Email}
End Function

更新如果结果需要LINQ,请返回IQueryable(Of Object)

Sub DataTest()
    Dim qry = GridView1_GetData
    Dim filteredQry = qry.Take(5)
End Sub
<德尔> 使用VB.NET比使用C#更容易,因为VB.NET支持后期绑定 - 即使变量`x`是`Object`类型,因此可能没有`UserName`属性,编译器将允许在运行时解析`UserName`。

这不像它可能有用,因为你不能将表达式传递给LINQ运算符,例如您可以使用.Take.Any的一次重载,但不能使用.Where

相关问题