【问题标题】:How can we perform a select into another select using Linq c# left join, count , sum, where我们如何使用 Linq c# left join, count , sum, where 执行一个选择进入另一个选择
【发布时间】:2017-06-29 17:30:03
【问题描述】:

如何将我的 sql 代码转换为 Linq 格式:

我们如何使用 Linq c# 将一个选择执行到另一个选择中:

我的sql代码:

SELECT DepartementProjects.Label, a.Number FROM
(SELECT DepartementProjects.Label ,count(1) as Number FROM DepartementProjects
inner join Absences on DepartementProjects.Id = Absences.DepartementProjectID
where Absences.Profil='SHT'
group by DepartementProjects.Label ) a right join DepartementProjects on DepartementProjects.Label = a.Label;

我的尝试:

            var AbsByDepartmentADM = from department in _dbContext.DepartementProjects
                                 join abs in _dbContext.Absences on department.Id equals abs.DepartementProjectID
                                 into groupedResult 
                                 from groupedResultRight in groupedResult.DefaultIfEmpty()
                                 group groupedResultRight by department.Label into grouped
                                 let NumberOfAbsence = grouped.Count(t => t.DepartementProjectID != null)
                                 let WorkedHours = grouped.Sum(a => a.WorkedHours != null ? a.WorkedHours : 0)

                                  select new
                                  {
                                      DepartmentId = grouped.Key,
                                      NumberOfAbsence,
                                      WorkedHours,
                                      AbsencesHours = (8 * NumberOfAbsence - WorkedHours),

                                  };

【问题讨论】:

  • 您尝试的解决方案不起作用怎么办?

标签: c# sql-server linq select join


【解决方案1】:

如果您尝试翻译 SQL,请先翻译任何子选择,然后是主选择,然后按 LINQ 短语顺序翻译。另外,您的 LINQ 添加了一些 SQL 中没有的值,所以我没有尝试更改 SQL 以匹配:

var sub = from dept in _dbContext.DepartementProjects
      join abs in _dbContext.Absences on dept.Id equals abs.DepartementProjectID into absj
      from abs in absj
      where abs.Profil == "SHT"
      group abs by dept.Label into absg
      select new { Label = absg.Key, Number = absg.Count() };

var ans = from dept in _dbContext.DepartementProjects
      join a in sub on dept.Label equals a.Label into lnj
      from ln in lnj.DefaultIfEmpty()
      select new { dept.Label, ln.Number };

【讨论】:

  • 感谢您的重播 为了避免强制转换异常,我们必须将 int 强制转换为 (int?) Number = (int?)absg.Count()
  • 我认为这是可能的,但这确实取决于 LINQ 提供程序。
  • 感谢您的回复,对我很有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-14
  • 1970-01-01
  • 2020-08-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多