Here is my query. UserName
column is citext
, having non-unique index on it.
var logs = Db.Logs .GroupBy(x => x.UserName) .ToDictionary(g => g.Key, g => g.Max(m => m.Time));
I’m getting an exception:
System.ArgumentException: An item with the same key has already been added
I don’t understand, how is it possible to be any dupe keys in resultant dictionary, if grouped values can’t have dupes by design?
P.S.
I have an update on this. While investigating, I’ve looked into generated sql for GroupBy
statement and got stuck (see below). Why group by
interpreted as order by
instead??
SELECT x."Time", x."UserName" FROM "UserAccessLogs" AS x ORDER BY x."UserName" NULLS FIRST
Advertisement
Answer
Well, seems that is a kind of ‘documented behavior‘. Grouping for further manipulation (like ToDictionary
f.e.) requires anonymous type representation before. I rewrote my query as
var logs = Db.Logs .GroupBy(x => x.UserName) .Select(g => new { UserName = g.Key, Time = g.Max(m => m.Time)}) .ToDictionary(d => d.UserName, d => d.Time);
and it works as expected. That’s why EF was interpreting my query wrong and that’s why I was getting a ‘dupe keys‘ error.