【问题标题】:LINQ: The query operator 'ElementAtOrDefault' is not supportedLINQ:不支持查询运算符“ElementAtOrDefault”
【发布时间】:2010-11-08 21:19:58
【问题描述】:

为什么下面的代码会产生错误?

不支持查询运算符“ElementAtOrDefault”

Dim Im = (From view In Db.Views Where _
               view.Pass = txtCode.Text _
          Select New With {.Id = view.UniqueID.ToString}_
          ).Distinct

Response.Redirect("~/test.aspx?x=" & Im(0).Id)

有什么方法可以在不使用 FirstOrDefault 选项的情况下修复它?

更新:这里是 StackTrace

   at System.Data.Linq.SqlClient.QueryConverter.VisitSequenceOperatorCall(MethodCallExpression mc)
   at System.Data.Linq.SqlClient.QueryConverter.VisitMethodCall(MethodCallExpression mc)
   at System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node)
   at System.Data.Linq.SqlClient.QueryConverter.ConvertOuter(Expression node)
   at System.Data.Linq.SqlClient.SqlProvider.BuildQuery(Expression query, SqlNodeAnnotations annotations)
   at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)
   at System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute[S](Expression expression)
   at System.Linq.Queryable.ElementAtOrDefault[TSource](IQueryable`1 source, Int32 index)
   at Login.btnLogin_Click(Object sender, EventArgs e) in D:\Projects\Memoria\Login.aspx.vb:line 14
   at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
   at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
   at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
   at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
   at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

【问题讨论】:

    标签: asp.net vb.net linq anonymous-types


    【解决方案1】:

    您需要做的是在查询末尾添加.ToList()。这应该有效:

    Dim Im = (From view In Db.Views Where _
               view.Pass = txtCode.Text _
          Select New With {.Id = view.UniqueID.ToString}_
          ).Distinct.ToList()
    
    Response.Redirect("~/test.aspx?x=" & Im(0).Id)
    

    没有.ToList(),查询只返回一个DataQuery(Of T) 而不是一个List(Of T)。添加 ToList 调用有两个作用:

    1. 强制查询立即执行,并且
    2. 返回支持 ElementAtOrDefault() 的集合类型

    希望有帮助!

    【讨论】:

    • 没错,因为我返回的是匿名类型
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-06
    • 1970-01-01
    • 2018-02-17
    • 1970-01-01
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多