3

I'm trying to manipulate properties in a GroupBy clause to be used in a dictionary:

var lifeStages = await _dbContext.Customers
                                 .GroupBy(x => GetLifeStage(x.DoB))
                                 .Select(x => new { LifeStage = x.Key, Count = x.Count() })
                                 .ToDictionaryAsync(x => x.LifeStage, x => x.Count);

I'm expecting results like

adolescent: 10, adult: 15, senior: 12 etc

But getting error:

Either rewrite the query in a form that can be translated,
    or switch to client evaluation explicitly 
    by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). 

Offcourse I can't combine ToDictionary() with any of the mentioned calls, and splitting up the query did not resolve the issues or taught my anything)

I've tried with making GetLifeStage() static and async, no difference there as well. The method gets called, performs what it needs to do, and still GroupBy can't be translated

If I leave out the Select() part and work with the Key of the GroupBy, same error: "...could not be translated."

I saw an error too that said I couldn't combine a GroupBy() with a ToDictionary() during try-outs, but doesn't seem to pop up atm.

As I'm running out of ideas, all suggestions are welcome!

update:

private LifeStage GetLifeStage(DateTimeOffset doB)
{
  var ageInMonths = Math.Abs(12 * (doB.Year - DateTimeOffset.UtcNow.Year) + doB.Month - DateTimeOffset.UtcNow.Month);

  switch (ageInMonths)
  {
    case < 216:
      return LifeStage.Adolescent;
    case < 780:
      return LifeStage.Adult;
    case >= 780:
      return LifeStage.Senior;
  }
}
7
  • 1
    "I've tried with making GetLifeStage() static and async, no difference there as well. The method gets called.." That's the problem - methods that are translated are not called. Query translator identifies known methods and translates (converts) them to the corresponding SQL syntax without calling them. That's why custom (unknown) methods cannot be translated. Remember that the query translation happens at runtime, and translator is code like any other - it's not a compiler, has no source code and cannot see what is inside your method.
    – Ivan Stoev
    Sep 15, 2020 at 18:06
  • @IvanStoev Thanks for your clear explanation. So my options are to write my own extension Linq, or GroupBy DoB and process the dictionary-data afterwards with no Linq?
    – BHANG
    Sep 15, 2020 at 19:00
  • 1
    You are welcome. The best would be to replace GetLifeStage method call with inline translatable expression. If you could do that, the rest of the code would work w/o modification. Can you post the GetLifeStage method body to see if that's possible?
    – Ivan Stoev
    Sep 15, 2020 at 19:25
  • 1
    No raw SQL, just regular C# expression. Normally the switch could be replaced with conditional operators (condition1 ? result1 : condition2 ? result2 : ...). The problem here is though is that EF Core does not support translation of DateTimeOffset members. If the property type was DateTime, then it could easily be translated. What EF Core version are you targeting?
    – Ivan Stoev
    Sep 15, 2020 at 19:49
  • 1
    Sorry, actually EFC supports DateTimeOffset properties/methods needed.
    – Ivan Stoev
    Sep 15, 2020 at 20:05

1 Answer 1

4

The problem is the usage of the custom GetLifeStage method inside the GroupBy expression. Custom methods cannot be translated to SQL because the query translator code has no way to know what is inside that method. And it cannot be called because there are no objects at all during the translation process.

In order to make it translatable, you have to replace the custom method call with its body, converted to translatable expression - basically something which can be used as expression bodied method. You can't use variables and switch, but you can use conditional operators. Instead of variable, you could use intermediate projection (Select).

Here is the equivalent translatable query:

var lifeStages = await _dbContext.Customers
    .Select(c => new { Customer = c, AgeInMonths = Math.Abs(12 * (c.DoB.Year - DateTimeOffset.UtcNow.Year) + c.DoB.Month - DateTimeOffset.UtcNow.Month) })
    .GroupBy(x => x.AgeInMonths < 216 ? LifeStage.Adolescent : x.AgeInMonths < 780 ? LifeStage.Adult : LifeStage.Senior)
    // the rest is the same as original
    .Select(x => new { LifeStage = x.Key, Count = x.Count() })
    .ToDictionaryAsync(x => x.LifeStage, x => x.Count);
1
  • 2
    Big Thanks for the excellent explanation! Got my ass kicked real hard, but you made up for it with a great piece of knowledge! I'm testing atm, like you expected first, I indeed get an error with DateTimeOffsets, but won't let that stop me ;-)) Thank you very much!
    – BHANG
    Sep 15, 2020 at 20:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.