The problem is that the .Aggregate()
call is part of the projection to some type, and adding a .ToList()
call inside the projection won't work since that projection is translated to sql as a whole. You cannot tell EF to translate half of the projection to SQL, and the other half not. You have to split the projection in two parts, and tell EF to translate the first part, but not the second.
Ok, to solve this. At the moment you have something like this. I can't be specific, and it will be different from your query, since you do not show the full query.
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();
To eliminate the .Aggregate()
call in the projection, you need to leave the datasource of the Aggregate
intact so L2E can take that data from the database. After that you can apply the .Aggregate()
in-memory.
var result = ctx.SomeTable
.Where(...whatever...)
// Change: Do not project to an entity, but to an anonymous type
.Select(x => new {
// lots of properties
// Change: Removed the Aggregate-part
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 + " | ",
// Added: New property for the aggregate-datasource
RelatedAdresses = m.RelatedMultipleWorks
.Select(z =>
z.RelatedCity + " + " + z.RelatedCounty + " + " + z.RelatedDistrict + " + " +
z.RelatedNeighborhood + " + " + z.RelatedStreet + " + " + z.RelatedRoad
)
// other properties
})
// Added: Call AsEnumerable to stop translating to SQL
.AsEnumerable()
// Added: Project again, fairly simple since all properties are already ok, but now call the Aggregate
.Select(x => new SomeEntity {
// lots of properties
Adresses = Adresses + RelatedAdresses.Aggregate((current, next) => current + " | " + next)
// other properties
})
.ToList();