EntityFramework Unable to create a constant value of type 'Anonymous type'. Only primitive types or enumeration types are supported in this context

c# entity-framework linq

Accepted Answer

DistinctBy (Is it 6 zz zz?) is most likely merely a LINQ-to-Objects extension method (i.e. forIEnumerable<T> not withIQueryable<T> Consequently, calling it executes the database query up to this point and produces aposts memory collection (not aIQueryable<Post> ) that results in the exception in the second search atposts.Any... due to the fact that with regards to the second SQL queryposts is currently a collection of "constant" objects, which LINQ-to-Entities does not support. Additionally, it triggers that sorting,Skip and Take are carried out in memory rather than the database, potentially adding needless overhead and loading considerably more data than necessary.

In an effort to preventDistinctBy and substitute the following, which ought to returnposts as IQueryable<Post> :

var posts = dbContext
    .Where(x => channels.Contains(x.Connection))
    .GroupBy(p => new { p.Medium, p.ID })
    .Select(g => g.FirstOrDefault()) // gives the first Post in each group
    .OrderByDescending(x => x.Date)
9/30/2013 3:14:26 PM

Popular Answer

Do theToList() call before the anonymous class is created (Select(x => new { x.ItemId, x.Tags }) )

var dicTags= dbContext.PostTagRelation
   .Where(x => posts.Any(g => g.ItemId == x.ItemId && g.Medium == x.Medium)
       && x.Company == companyId)
   //force execution of the query
   //now you have an IEnumerable instead of IQueryable
   .ToDictionary(g => g.ItemId, g => g.Tags);

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow