C# EntityFramework无法创建类型为';匿名类型';。在此上下文中仅支持基元类型或枚举类型
我正在尝试对我的实体执行C# EntityFramework无法创建类型为';匿名类型';。在此上下文中仅支持基元类型或枚举类型,c#,linq,entity-framework,C#,Linq,Entity Framework,我正在尝试对我的实体执行ToDictionary(),但我不断收到此错误或类似的另一个错误,但消息中显示了我的实体: 无法创建“匿名类型”类型的常量值。只有 在此上下文中支持基元类型或枚举类型 或者这个错误消息中包含我的实体: 无法创建类型为的常量值 “DataAccess.Posts”。只有基元类型或 在此上下文中支持枚举类型 我将查询分解为一些较小的peace,但仍然得到以下错误MSG之一: var posts = dbContext .Posts .Where(x =>
ToDictionary()
,但我不断收到此错误或类似的另一个错误,但消息中显示了我的实体:
无法创建“匿名类型”类型的常量值。只有
在此上下文中支持基元类型或枚举类型
或者这个错误消息中包含我的实体:
无法创建类型为的常量值
“DataAccess.Posts”。只有基元类型或
在此上下文中支持枚举类型
我将查询分解为一些较小的peace,但仍然得到以下错误MSG之一:
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);
var posts=dbContext
.职位
.其中(x=>channels.Contains(x.Connection))
.DistinctBy(p=>new{p.Medium,p.ID})
.OrderByDescending(x=>x.Date)
.Skip(Skip)
.拿(拿);
var asociatedTags=dbContext
.后置关系
.Where(x=>posts.Any(g=>g.ItemId==x.ItemId&&g.Medium==x.Medium)
&&x.公司==公司ID)
.Select(x=>new{x.ItemId,x.Tags})
.ToList();
Dictionary dicTags=新字典();
dicTags=asociatedTags.ToDictionary(g=>g.ItemId,g=>g.Tags);
我看到了一些关于这方面的帖子,但我不能把它们和我的情况放在一起
任何帮助都将不胜感激 在创建匿名类之前执行ToList()
调用(Select(x=>new{x.ItemId,x.Tags})
)
DistinctBy
(是吗?)可能只是LINQ到对象的一种扩展方法(即对于IEnumerable
,而不是IQueryable
)。这意味着,调用它将执行DB查询到此点,结果是内存中的posts
集合(而不是IQueryable
),这会在posts的第二个查询中导致异常。任何…
,因为对于第二个SQL查询posts
现在是“常量”的集合LINQ不支持的对象到实体。此外,它还导致排序、Skip
和Take
在内存中执行,而不是在数据库中执行,这可能会带来不必要的开销,并且加载的数据比您需要的多得多
您可以尝试通过避免差异,并用以下内容替换它,这些内容应返回posts
作为IQueryable
:
如果有任何问题:.DistinctBy()
是一种非常简单的方法。谷歌说它附带了更多的LINQ。没错,它是LINQ
DistinctBy
上的一个扩展,可能只是LINQ对对象的一个扩展(即IEnumerable
,而不是IQueryable
)。这意味着,调用它将执行DB查询到此点,结果是内存中的posts
集合,这将在posts.Any…
的第二次查询中导致异常。此外,它还导致排序、Skip
和Take
在内存中执行,而不是在数据库中执行,加载的数据比您需要的多得多。我要说的是,避免使用
区分。如果我丢失了区分我会得到重复的帖子。我可以用什么来代替DistinctBy
?可能类似于:GroupBy(p=>new{p.Medium,p.ID})。选择(g=>g.FirstOrDefault())
。
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);
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);