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

EF Core 7中多对多表的INNER JOIN、GROUP BY、HAVING COUNT()实现

EF Core 7(PostgreSQL)对应SQL查询的实现方案

针对你给出的SQL查询和实体模型,以下两种EF Core实现方式均可生成等价的PostgreSQL查询:

1. LINQ查询语法

var query = from q in context.Questionnaires
            from qs in q.Sections
            from sq in qs.Section.Questions
            group sq by new { q.Id, sq.Question.Id } into g
            where g.Count() > 1
            select new 
            {
                QuestionnaireId = g.Key.Id,
                QuestionId = g.Key.Id1,
                Count = g.Count()
            };

var result = query.ToList();

2. 方法链(Fluent API)语法

var query = context.Questionnaires
    .SelectMany(q => q.Sections, (q, qs) => new { q, qs })
    .SelectMany(x => x.qs.Section.Questions, (x, sq) => new { x.q.Id, sq.Question.Id })
    .GroupBy(g => new { g.Id, g.Id1 })
    .Where(g => g.Count() > 1)
    .Select(g => new 
    {
        QuestionnaireId = g.Key.Id,
        QuestionId = g.Key.Id1,
        Count = g.Count()
    });

var result = query.ToList();

说明

  • 两种方式都会生成与目标SQL结构一致的查询语句,EF Core会自动适配PostgreSQL的带引号列名规则(比如映射q.Id到q."Id")。
  • 依赖实体模型中定义的导航属性(Questionnaire.Sections、Section.Questions等),默认约定下EF Core会自动识别这些关联关系。
  • 查询结果返回匿名类型,包含问卷ID、问题ID以及问题重复出现的次数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 16:22:23