[使用GroupBy时出现System.InvalidOperationException

问题描述 投票:1回答:1

我有以下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; } 
}

目标是计算每个标签关联多少个帖子。

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

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().

我想念什么吗?

entity-framework-core linq-to-entities entity-framework-core-3.1
1个回答
1
投票

该组中的问题是Tag是导航属性,因此不能将其用作列。为了解决此问题,请使用TagId导航中的NameTag。道具,这是我想分组的两列:

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();
© www.soinside.com 2019 - 2024. All rights reserved.