2013-10-18 16 views
5

Errore: LINQ alle entità non riconosce il metodo 'System.String Aggregate [String, String] (System.Collections.Generic.IEnumerable 1[System.String], System.String, System.Func 3 [System.String, System. String, System.String]) 'metodo, e questo metodo non può essere tradotto in un'espressione di archivio.La funzione aggregata nell'espressione LINQ genera errore. (non può essere tradotto in un'espressione di negozio.)

Linq Expression:

 Items = context.TESTANSWER.Where(x => x.ID == 6729223232) 
      .Join(context.QUESTIONREPOs, x => x.QUESTIONID, y => y.ID, (x, y) => new { x = x, y = y }) 
      .Join(context.OPTIONREPOs, p => p.x.QUESTIONID, q => q.QUESTIONID, (p, q) => new { p = p, q = q }).Where(p => p.p.x.RESPONSEID == p.q.ID) 
      .GroupJoin(context.TESTANSWERASSOCIATION, c => c.p.x.ID, b => b.TESTANSWERID, (c, b) => new { c = c, b = b }) 
      .SelectMany(
       n => n.b.DefaultIfEmpty(), 
        (n, b) => 
         new QuestListItemObj 
         { 
          State = n.c.p.x.STATE, 
          Association = n.b.Select(l => l.ASSOCIATION.TITLE).ToList().Aggregate((s, t) => s + ", " + t), 
          Description = n.c.p.y.DESCRIPTION, 
          Question = n.c.p.y.QUESTION, 
          Answer = n.c.q.OPTIONTEXT, 
         }).ToList(); 

Inoltre ho appena provato SelectMany ma ho ottenuto lo stesso errore ..

Affiliaiton = n.b.SelectMany(l => l.AFFILIATION.TITLE).Aggregate(string.Empty, (s, t) => s + ", " + t), 

risposta

5

hai un IQueryable che si traduce in SQL. Il tuo Aggregate è un metodo sconosciuto a SQL, quindi non c'è modo di tradurlo e ottieni la tua eccezione.

Un modo possibile è chiamare AsEnumerable() prima. Ciò causerà l'esecuzione della query e otterrà i dati dal server SQL e le azioni rimanenti verranno eseguite in memoria (e non su SQL Server).

myQuery.AsEnumerable().Aggregate(...) 
3

Come indica il messaggio di errore, il database non sa come tradurre quel codice in SQL.

Fortunatamente, non c'è davvero bisogno di farlo. Piuttosto che inserire i dati in una stringa delimitata da virgola sul lato DB, basta tirare giù i pezzi e ricavarne una stringa in C#. Sta tirando la stessa quantità di dati, quindi non c'è una vera ragione per usare un database.

È possibile utilizzare AsEnumerable per garantire che la seguente operazione è quello in LINQ di opporsi, non alla fine di DB, ma in questo caso Aggreagte è uno strumento povero da utilizzare per l'aggiunta dei valori in una stringa. Basta usare String.Join.

var query = n.b.SelectMany(l => l.AFFILIATION.TITLE); 


//not very efficient option, but will work 
string data1 = query.AsEnumerable(). 
    .Aggregate(string.Empty, (s, t) => s + ", " + t); 

//faster, more efficient, simpler to write, and clearer to the reader. 
string data2 = string.Join(", ", query); 
Problemi correlati