You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# LINQ查询返回多行问题:需返回含多条reviews的单条结果

解决方案

修改你的LINQ查询,避免直接关联TblReviews(这会导致每条评论生成一条结果),改为在投影时获取当前组件对应的评论集合,同时修正评分计算逻辑(原逻辑是统计全表评论,而非当前组件的):

var componentData = from comps in ctx.TblControls
                    join tags in ctx.TblTags on comps.TagId equals tags.Id
                    join framework in ctx.TblFrameworks on comps.FrameworkId equals framework.Id
                    where comps.Guid == guid
                    select new
                    {
                        ratingTotal = ctx.TblReviews
                            .Where(x => x.ControlId == comps.Id)
                            .Sum(x => x.Rating), // 直接Sum替代逐个计数相乘,逻辑一致且更简洁
                        ratingValue = ctx.TblReviews
                            .Where(x => x.ControlId == comps.Id)
                            .Count(),
                        reviews = ctx.TblReviews.Where(x => x.ControlId == comps.Id).ToList(),
                        tags,
                        framework,
                        comps
                    };

return View(new { componentData = componentData.FirstOrDefault() });

如果你的实体类已配置EF导航属性(比如TblControls包含ICollection<TblReviews> Reviews、TblTags Tags、TblFrameworks Framework),可以用预加载简化代码,提升查询效率:

var componentData = from comps in ctx.TblControls
                    .Include(c => c.Reviews)
                    .Include(c => c.Tags)
                    .Include(c => c.Framework)
                    where comps.Guid == guid
                    select new
                    {
                        ratingTotal = comps.Reviews.Sum(x => x.Rating),
                        ratingValue = comps.Reviews.Count(),
                        reviews = comps.Reviews,
                        tags = comps.Tags,
                        framework = comps.Framework,
                        comps
                    };

return View(new { componentData = componentData.FirstOrDefault() });

核心修改点

  • 移除与TblReviews的直接关联,改为通过ControlId过滤获取当前组件的评论集合,确保每个组件仅生成一条结果
  • 优化评分计算逻辑,仅统计当前组件的评论数据,避免全表统计的错误
  • 导航属性+预加载的方式能减少重复查询,让代码更简洁高效

内容的提问来源于stack exchange,提问作者redoc01

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 22:01:14