2010-11-08 4 views
6

Perché il codice seguente genera l'errore?LINQ: l'operatore di query 'ElementAtOrDefault' non è supportato

L'operatore query 'ElementAtOrDefault' non è supportato

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) 

C'è un modo di risolverlo senza usare l'opzione FirstOrDefault?

UPDATE: Ed ecco 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) 

risposta

10

Quello che dovete fare è aggiungere .ToList() alla fine della query. Questo dovrebbe funzionare:

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) 

Senza .ToList(), la query solo restituisce un DataQuery (Of T) al posto di un elenco (Of T). Aggiunta la chiamata ToList fa due cose:

  1. Forze query per eseguire immediatamente, e
  2. Restituisce un tipo di raccolta che supporta ElementAtOrDefault()

Speranza che aiuta!

+0

È vero, dal momento che sto restituendo il tipo anonimo – OrElse