基于连接表将计数列添加到LINQ查询

时间:2017-04-25 20:07:42

标签: c# sql linq asp.net-mvc-5 entity-framework-6

所以我有一个我创建的SQL视图,它提供了我需要的东西。从本质上讲,它是一个工作岗位投标系统,显示已经批准了多少职位与填补(或分配)。

SELECT Companies.Name AS Company, Grades.Name AS Grade, Series.Name
AS Series, Positions.Authorized, COUNT(People.PersonId) AS Assigned

FROM Companies INNER JOIN
     Positions ON Companies.Id = Positions.CompanyId INNER JOIN
     Series ON Positions.SeriesId = Series.Id INNER JOIN
     Grades ON Positions.GradeId = Grades.Id INNER JOIN
     People ON Positions.CompanyId = People.CompanyId AND
     Positions.SeriesId = People.SeriesId AND Positions.GradeId = People.GradeId

GROUP BY Companies.Name, Grades.Name, Series.Name, Positions.Authorized

Authorized SQL Query

现在我想要做的是在LINQ查询中重新创建它。我差点把它拿到我需要的地方;但是,我无法弄清楚如何在最后基于表添加计数列。

这是我当前的LINQ查询:

var query = from a in db.Companies
            join b in db.Positions on a.Id equals b.CompanyId
            join c in db.Series on b.SeriesId equals c.Id
            join d in db.Grades on b.GradeId equals d.Id
            join e in db.People on new { b.CompanyId, b.SeriesId, b.GradeId } equals new { e.CompanyId, e.SeriesId, e.GradeId }
            group a by new { CompanyName = a.Name, GradeName = d.Name, SeriesName = c.Name, b.Authorized, e.PersonId } into f
            select new { Company = f.Key.CompanyName, Grade = f.Key.GradeName, Series = f.Key.SeriesName, f.Key.Authorized, Assigned = /* needs to be Count(People.PersonId) based on last join */ )};

提前感谢您提供的任何帮助!

1 个答案:

答案 0 :(得分:0)

想出来。之所以发布多行并且没有对同一行进行适当的计数是因为在我的" group by"我加入了" e.PersonId"应该简单地删除它。我还必须添加一些东西才能使它在前端剃刀视图上工作,因为它是一个匿名类型(这与原始问题没有任何关系,但我认为我' d给出改变的理由)。所以删除答案的人,你是部分正确的,但是它不起作用的原因是因为该组中的额外字段:

dynamic query = (from a in db.Companies
                    join b in db.Positions on a.Id equals b.CompanyId
                    join c in db.Series on b.SeriesId equals c.Id
                    join d in db.Grades on b.GradeId equals d.Id
                    join e in db.People on new { b.CompanyId, b.SeriesId, b.GradeId } equals new { e.CompanyId, e.SeriesId, e.GradeId }
                    group a by new { CompanyName = a.Name, GradeName = d.Name, SeriesName = c.Name, b.Authorized } into f
                    select new { Company = f.Key.CompanyName, Grade = f.Key.GradeName, Series = f.Key.SeriesName, Authorized = f.Key.Authorized, Assigned = f.Count()}).AsEnumerable().Select(r => r.ToExpando());

页面上的内容如下:

Converted Authorized LINQ razor page sample