I have a linq query:
DbSet<GeneralGroup>()
.Where(...)
...
.Select(res => new GeneralGroupResult{
Id = result.Id,
Statistics = new Statistics(
res.GeneralCount,
res.SpecificCount
)
});
Once I run it in database context with .ToListAsync()
, it works fine.
I need to support dynamic sorting. For example, when I receive Id
, I generate the following expression:
{Param_0 => Convert(Param_0.Id, Object)}
Then I apply it to query with
query.OrderBy(expression)
So it becomes like this:
...
.Select(res => new GeneralGroupResult{
Id = result.Id,
Statistics = new Statistics(
res.GeneralCount,
res.SpecificCount
)
})
.OrderBy(namelessParameter{0} => (object)namelessParameter{0}.Id)
And that also works fine.
Same approach doesn't work with nested properties though. When I receive Statistics.SpecificCount
and generate expression for it:
{Param_0 => Convert(Param_0.Statistics.SpecificCount, Object)}
I get this as evaluated expression:
...
.Select(res => new GeneralGroupResult{
Id = result.Id,
Statistics = new Statistics(
res.GeneralCount,
res.SpecificCount
)
})
.OrderBy(namelessParameter{0} => (object)namelessParameter{0}.Statistics.SpecificCount)
Which looks correct, but fails to translate to SQL with the following error:
Error creating query string: The LINQ expression 'DbSet<GeneralGroup>()
.Where(...)
...
.OrderBy(ti2 => (object)new Statistics(
ti2.Inner.SpecificCount,
ti2.Inner.GeneralCount
).SpecificCount)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information..
Any idea what am I missing here?