asp.net – LINQ:不支持查询运算符’ElementAtOrDefault’

前端之家收集整理的这篇文章主要介绍了asp.net – LINQ:不支持查询运算符’ElementAtOrDefault’前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
为什么以下代码会产生错误

The query operator ‘ElementAtOrDefault’ is not supported

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)

解决方法

您需要做的是将.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调用有两个作用:

>强制查询立即执行,和
>返回支持ElementAtOrDefault()的集合类型

希望有所帮助!

原文链接:https://www.f2er.com/aspnet/245746.html

猜你在找的asp.Net相关文章