2010-11-08 12 views
6

¿Por qué el siguiente código produce el error?LINQ: El operador de consulta 'ElementAtOrDefault' no es compatible

El operador de consulta 'ElementAtOrDefault' no se admite

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) 

¿Hay alguna manera de arreglarlo sin utilizar la opción FirstOrDefault?

ACTUALIZACIÓN: Y aquí es la 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) 

Respuesta

10

Lo que hay que hacer es añadir .ToList() hasta el final de la consulta. Esto debería funcionar:

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) 

Sin .ToList(), la consulta sólo devuelve un DataQuery (Of T) en vez de una lista (Of T). La adición de la llamada ToList hace dos cosas:

  1. Fuerzas de la consulta se ejecute inmediatamente, y
  2. devuelve un tipo de colección que apoya ElementAtOrDefault()

Espero que ayude!

+0

Eso es cierto, ya que estoy volviendo tipo anónimo – OrElse

Cuestiones relacionadas