System.InvalidOperationException 使用 GroupBy 时

System.InvalidOperationException when using GroupBy

我有以下 EntityFramework Core 3.1 查询:

var counts = await postTags
  .GroupBy(x => x.Tag)
  .Select(x => new Model {
    Tag = new TagModel { 
      Id = x.Key.Id, 
      Name = x.Key.Name
    },
    PostCount = x.Count() 
  })
  .ToListAsync();

实体所在位置:

public class Tag {
  public Int32 TagId { get; set; }
  public String Name { get; set; } 
  public virtual Collection<PostTag> PostTags { get; set; } 
}

public class PostTag {
  public Int32 PostId { get; set; }
  public Int32 TagId { get; set; }
  public virtual Post Post { get; set; } 
  public virtual Tag Tag { get; set; } 
}

public class Post {
  public Int32 PostId { get; set; }
  public String Name { get; set; } 
  public virtual Collection<PostTag> PostTags { get; set; } 
}

objective 计算每个标签关联的帖子数。

当我 运行 查询时,出现以下错误:

Exception thrown: 'System.InvalidOperationException' in System.Private.CoreLib.dll: 'The LINQ expression 'DbSet<PostTag>
    .Join(
        outer: DbSet<Tag>, 
        inner: j => EF.Property<Nullable<int>>(j, "TagId"), 
        outerKeySelector: s => EF.Property<Nullable<int>>(s, "Id"), 
        innerKeySelector: (o, i) => new TransparentIdentifier<PostTag, Tag>(
            Outer = o, 
            Inner = i
        ))
    .GroupBy(
        source: j => j.Inner, 
        keySelector: j => j.Outer)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync().

我是不是漏掉了什么?

群里的问题是Tag是一个导航属性,所以不能作为栏目使用。为了解决这个问题,请使用 Tag 导航中的 TagIdName。 prop 相反,这是我认为你想要分组的两列:

var counts = await postTags
  .GroupBy(x => new{ x.Tag.TagId, x.Tag.Name)
  .Select(x => new Model {
    Tag = new TagModel { 
      Id = x.Key.TagId, 
      Name = x.Key.Name
    },
    PostCount = x.Count() 
  })
  .ToListAsync();