2013-09-30 38 views
4

我試圖做我的實體ToDictionary(),但我不斷收到此錯誤或其他類似一個像這樣的,但我的實體信息中顯示:EntityFramework無法創建「匿名類型」類型的常量值。只有原始類型或枚舉類型在這方面的支持

無法創建「匿名類型」類型的常量值。在此上下文中僅支持 基元類型或枚舉類型。

或者這一個與我在錯誤味精實體:

無法創建類型 「DataAccess.Posts」的恆定值。在此上下文中僅支持基本類型或枚舉類型。

我打破了查詢到一些規模較小的和平年代,但仍然得到這些錯誤封郵件:

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); 

我碰到這個幾個帖子來了,但我不能把他們跟我的情況。

任何幫助真的很感謝!

+0

如果是的任何事情:'.DistinctBy()'是AFAIK沒有開箱即用的方法。谷歌說它帶有MoreLinq。 – Marco

+0

確實,它是'LINQ'上的擴展。 – Yustme

+0

'DistinctBy'可能只是LINQ到對象的擴展(即對於'IEnumerable ',而不是'IQueryable ')。這意味着,調用它執行數據庫查詢到這一點,結果是內存中的'posts'集合,導致在'posts.Any ...'第二個查詢中的異常。此外,它會導致在內存中執行排序,Skip和Take,而不是數據庫中的數據比您需要的數據更多。我會說,避免'DistinctBy'。 – Slauma

回答

4

DistinctBy(是this one?)大概只能爲一個擴展方法LINQ到對象(即用於IEnumerable<T>,不爲IQueryable<T>)。這意味着,調用它執行DB查詢到這一點,結果是內存中的posts集合(而不是IQueryable<Post>),導致在第二個查詢posts.Any...處發生異常,因爲相對於第二個SQL查詢posts現在是一個集合LINQ-to-Entities不支持的「常量」對象。此外,它會導致排序SkipTake在內存中執行,而不是在數據庫中執行,可能會產生不必要的開銷和大量加載的數據。

你可以儘量避免DistinctBy和它應該會返回替換爲以下postsIQueryable<Post>

var posts = dbContext 
    .Posts 
    .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) 
    .Skip(skip) 
    .Take(take); 
0

創建匿名類的前執行ToList()調用(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 
    .ToList() 
    //now you have an IEnumerable instead of IQueryable 
    .ToDictionary(g => g.ItemId, g => g.Tags); 
+0

生成關於帖子實體的相同錯誤消息:( – Yustme

相關問題