LINQ表达式中的聚合函数抛出错误。 (不能翻译成商店表达。)

错误:LINQ to Entities无法识别方法’System.String Aggregate [String,String](System.Collections.Generic.IEnumerable 1[System.String], System.String, System.Func 3 [System.String,System。 String,System.String])’方法,此方法无法转换为商店表达式。

Linq表达:

  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 => pxQUESTIONID, q => q.QUESTIONID, (p, q) => new { p = p, q = q }).Where(p => ppxRESPONSEID == pqID) .GroupJoin(context.TESTANSWERASSOCIATION, c => cpxID, b => b.TESTANSWERID, (c, b) => new { c = c, b = b }) .SelectMany( n => nbDefaultIfEmpty(), (n, b) => new QuestListItemObj { State = ncpxSTATE, Association = nbSelect(l => l.ASSOCIATION.TITLE).ToList().Aggregate((s, t) => s + ", " + t), Description = ncpyDESCRIPTION, Question = ncpyQUESTION, Answer = ncqOPTIONTEXT, }).ToList(); 

我也尝试了SelectMany但是得到了同样的错误..

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

你有一个转换为SQL的IQueryable 。 您的Aggregate是SQL不知道的方法,因此无法翻译它并且您获得exception。

一种可能的方法是之前调用AsEnumerable() 。 这将导致查询执行并从SQL服务器获取数据,其余操作将在内存中执行(而不是在SQL Server上)。

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

正如错误消息告诉您的那样,数据库不知道如何将该代码转换为SQL。

幸运的是,确实没有必要这样做。 而不是将数据放入DB端的逗号分隔字符串,只需拉下碎片并在C#中创建一个字符串。 它正在提取相同数量的数据,因此没有真正的理由使用数据库。

您可以使用AsEnumerable来确保以下操作是linq to object中的操作,而不是DB端,但在这种情况下, Aggreagte是一个很差的工具,用于将值附加到字符串。 只需使用String.Join

 var query = nbSelectMany(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);