我有这个LINQ查询,我的聚合部分有问题:
Adresses = m.RelatedMultipleWorks.Count == 0 ?
m.RelatedCity + " + " + m.RelatedCounty + " + " + m.RelatedDistrict + " + " +
m.RelatedNeighborhood + " + " + m.RelatedStreet + " + " + m.Road :
m.RelatedCity + " + " + m.RelatedCounty + " + " + m.RelatedDistrict + " + " +
m.RelatedNeighborhood + " + " + m.RelatedStreet + m.RelatedRoad + " | "
m.RelatedMultipleWorks.Select(z => z.RelatedCity + " + " + z.RelatedCounty + " + " +
z.RelatedDistrict + " + " + z.RelatedNeighborhood + " + " + z.RelatedStreet + " + " + z.RelatedRoad)
.Aggregate((current, next) => current + " | " + next),
我得到了这个例外。
{“LINQ to Entities无法识别方法'System.String Aggregate [String](System.Collections.Generic.IEnumerable
1[System.String], System.Func
3 [System.String,System.String,System.String])'方法,以及 此方法无法转换为商店表达式。“}
为什么我会收到此异常?我怎么能摆脱它?感谢。
答案 0 :(得分:4)
Aggregate没有转换为SQL,因此Enumerate
结果为内存:
.AsEnumerable().Aggregate((current, next) => current + " | " + next);
OR:
.ToList().Aggregate((current, next) => current + " | " + next);
答案 1 :(得分:1)
问题在于209: 1076: if (some condition) {
-: 1077: // some condition happen
2: 1078: LOG("some condition happen”);
-: 1079: return STATUS_DONE;
-: 1080: }
-: 1081:
408: 1082: if (another condition) {
调用是某种类型投影的一部分,并且在投影中添加.Aggregate()
调用无法正常工作,因为该投影已转换为sql 作为一个整体。你无法告诉EF将一半的投影转换为SQL,而另一半则不能。您必须将投影分成两部分,并告诉EF翻译第一部分,而不是第二部分。
好的,要解决这个问题。此刻你有这样的事情。我不具体,而且与您的查询不同,因为您没有显示完整的查询。
.ToList()
要消除投影中的var result = ctx.SomeTable
.Where(...whatever...)
.Select(x => new SomeEntity {
// lots of properties
Adresses = m.RelatedMultipleWorks.Count == 0 ?
m.RelatedCity + " + " + m.RelatedCounty + " + " + m.RelatedDistrict + " + " +
m.RelatedNeighborhood + " + " + m.RelatedStreet + " + " + m.Road :
m.RelatedCity + " + " + m.RelatedCounty + " + " + m.RelatedDistrict + " + " +
m.RelatedNeighborhood + " + " + m.RelatedStreet + m.RelatedRoad + " | "
m.RelatedMultipleWorks.Select(z => z.RelatedCity + " + " + z.RelatedCounty + " + " +
z.RelatedDistrict + " + " + z.RelatedNeighborhood + " + " + z.RelatedStreet + " + " + z.RelatedRoad)
.Aggregate((current, next) => current + " | " + next),
// other properties
})
.ToList();
调用,您需要保留.Aggregate()
的数据源不变,以便L2E可以从数据库中获取该数据。之后,您可以在内存中应用Aggregate
。
.Aggregate()