I'm trying to do a ToDictionary()
on my entities but I keep getting this error or another one similar like this one but with my entities shown in the message:
Unable to create a constant value of type 'Anonymous type'. Only primitive types or enumeration types are supported in this context.
Or this one with my entity in the error msg:
Unable to create a constant value of type 'DataAccess.Posts'. Only primitive types or enumeration types are supported in this context.
I broke the query down to some smaller peace's but still getting either of these error msgs:
var posts = dbContext
.Posts
.Where(x => channels.Contains(x.Connection))
.DistinctBy(p => new { p.Medium, p.ID })
.OrderByDescending(x => x.Date)
.Skip(skip)
.Take(take);
var asociatedTags = dbContext
.PostTagRelation
.Where(x => posts.Any(g => g.ItemId == x.ItemId && g.Medium == x.Medium)
&& x.Company == companyId)
.Select(x => new { x.ItemId, x.Tags })
.ToList();
Dictionary<string, Tags> dicTags = new Dictionary<string, Tags>();
dicTags = asociatedTags.ToDictionary(g => g.ItemId, g => g.Tags);
I came across a few posts about this, but I can't place them with my situation.
Any help would really be appreciated!
.DistinctBy()
is afaik no Out of the box method. Google says it comes with MoreLinq. – MarcoLINQ
. – YustmeDistinctBy
is probably only an extension for LINQ-to-Objects (i.e. forIEnumerable<T>
, not forIQueryable<T>
). That means, calling it executes the DB query to this point and the result is aposts
collection in memory which causes the exception in the second query atposts.Any...
. Moreover it causes that sorting,Skip
andTake
are performed in memory and not in the database with much more loaded data than you need. I'd say, avoidDistinctBy
. – SlaumaDistinctBy
I'll get duplicate posts. What can I use in stead ofDistinctBy
? – YustmeGroupBy(p => new { p.Medium, p.ID }).Select(g => g.FirstOrDefault())
. – Slauma