I have the following EntityFramework Core 3.1 query:
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();
Where the entities are:
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; }
}
The objective is count how many Posts each tag is associated.
When I run the query I get the following error:
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().
Am I missing something?
The problem in the group is that Tag
is a navigation property, so can't use it as a column. In order to fix that use TagId
and Name
from Tag
nav. prop instead, which are the two columns I think you want to group:
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();