开发者

LINQ: The query operator 'ElementAtOrDefault' is not supported

开发者 https://www.devze.com 2023-01-24 05:47 出处:网络
Why the following code produces the error? The query operator \'ElementAtOrDefault\' is not supported Dim Im = (From view In Db.Views Where _开发者_JAVA技巧

Why the following code produces the error?

The query operator 'ElementAtOrDefault' is not supported

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

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

Is there any way of fixing it without using the FirstOrDefault option?

UPDATE: And here is the 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)


What you need to do is add .ToList() to the end of your query. This should work:

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)

Without .ToList(), the query just returns a DataQuery(Of T) instead of a List(Of T). Adding the ToList call does two things:

  1. Forces the query to execute immediately, and
  2. Returns a collection type that supports ElementAtOrDefault()

Hope that helps!

0

精彩评论

暂无评论...
验证码 换一张
取 消