我想创建一个路由获取关于主题的统计信息,所以我尝试使用join和groupBy来实现它,我想要的结果显示categoryId,标题,正文和每个类别的总主题,但我得到了这个错误与我的实现。
。GroupBy (x =比;X.title)'无法翻译。要么以可翻译的形式重写查询,要么通过插入对'AsEnumerable', 'AsAsyncEnumerable', 'ToList'或'ToListAsync'的调用显式切换到客户端求值
请问有人知道如何解决这个问题吗?
public class Topic
{
public int Id { get; set; }
public string TItle { get; set; }
public string body { get; set; }
public int CategoryId { get; set; }
[JsonIgnore]
public Category Category { get; set; }
}
public class Category
{
public int Id { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Description { get; set; }
}
[HttpGet("stats")]
public async Task<ActionResult> getTopicStats()
{
var stats = _context.Topics.Join(
_context.Categories,
topic => topic.CategoryId,
cat => cat.Id,
(topic, cat) => new
{
catId = topic.CategoryId,
desc = cat.Description,
title = cat.Title
}).GroupBy(x => x.title);
await stats.ToListAsync();
Console.WriteLine(stats);
}
不要加入LINQ-to-Entities。只要按照你的导航属性。
希望结果显示类别id,标题,正文和每个类别的总主题
有了合适的导航属性,
public class Category
{
public int Id { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Description { get; set; }
public ICollection<Topic> Topics {get; set;} = new HashSet<Topic>();
}
这就像:
from c in db.Categories
select new
{
c.CategoryId,
CategoryTitle = c.Title,
CategoryDescription = c.Description,
TopicCount = c.Topics.Count()
};