【发布时间】:2013-09-30 11:06:44
【问题描述】:
我正在尝试对我的实体执行ToDictionary(),但我不断收到此错误或另一个类似的错误,但消息中显示了我的实体:
无法创建“匿名类型”类型的常量值。仅有的 在此上下文中支持原始类型或枚举类型。
或者这个错误信息中有我的实体:
无法创建类型的常量值 '数据访问.帖子'。只有原始类型或 在此上下文中支持枚举类型。
我将查询分解为一些较小的和平,但仍然收到以下错误消息:
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);
我看到了一些关于此的帖子,但我无法将它们与我的情况联系起来。
任何帮助将不胜感激!
【问题讨论】:
-
如果有任何问题:
.DistinctBy()是 afaik 没有开箱即用的方法。谷歌表示它带有 MoreLinq。 -
没错,它是
LINQ的扩展。 -
DistinctBy可能只是 LINQ-to-Objects 的扩展(即IEnumerable<T>,而不是IQueryable<T>)。这意味着,调用它会执行数据库查询,结果是内存中的posts集合,这会导致posts.Any...的第二个查询出现异常。此外,它会导致排序,Skip和Take在内存中执行,而不是在数据库中执行,加载的数据比您需要的多得多。我会说,避免DistinctBy。 -
如果我丢失了
DistinctBy,我会收到重复的帖子。我可以用什么代替DistinctBy? -
可能类似于:
GroupBy(p => new { p.Medium, p.ID }).Select(g => g.FirstOrDefault()).
标签: c# linq entity-framework