EntityFramework无法创建类型为“匿名类型”的常量值。在此上下文中仅支持原始类型或枚举类型

Yus*_*tme 5 c# linq entity-framework

我正在尝试ToDictionary()对我的实体执行操作,但我不断收到此错误或类似的另一个错误,但消息中显示了我的实体:

无法创建类型为“匿名类型”的常量值。在此上下文中仅支持原始类型或枚举类型。

或与我的实体一起出现此错误消息:

无法创建类型为“ 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);
Run Code Online (Sandbox Code Playgroud)

我遇到了一些有关此的帖子,但是我无法根据自己的情况来放置它们。

任何帮助将不胜感激!

Sla*_*uma 4

DistinctBy(是这个吗?)可能只是 LINQ-to-Objects 的一种扩展方法(即 for IEnumerable<T>,而不是 for IQueryable<T>)。这意味着,调用它会执行此时的数据库查询,结果是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);
Run Code Online (Sandbox Code Playgroud)