使用LINQ to Entities的外连接查询

use*_*842 6 c# linq linq-to-entities entity-framework

我公司有0到n个部门,1个部门有0到n个办公室,1个办公室有0到n个工作人员.现在我需要使用linq查询按部门列出员工的平均年龄,如果部门中没有人则默认平均是0.代码如下:

    DataContext ctx = new DataContext();

    var q0 = from d in ctx.Departments
             join o in ctx.Offices on d.Id equals o.DepartmentId
             join e in ctx.Employees on o.Id equals e.OfficeId
             group e by d into de
             select new {
                DepartmentId = de.Key.Id,
                AverageAge = de.Count() == 0 ? 0 : de.Average(e => e.Age),
             };


    var q1 = from d in ctx.Departments
             join de in q0 on d.Id equals de.DepartmentId into des
             from de in des.DefaultIfEmpty()
             select new
             {
                 DepartmentName = d.Name,
                 AverageAge = de == null ? 0 : de.AverageAge
             };

    var result = q1.ToList();
    foreach (var item in result)
    {
        Console.WriteLine("{0}-{1}", item.DepartmentName, item.AverageAge);
    }
    ctx.Dispose();
Run Code Online (Sandbox Code Playgroud)

但是如何将q0和q1组合成一个查询呢?

GMa*_*cci 7

    were you meaning something along the lines of:

var newQ2 = from d in ctx.Departments
                 outer left join o in ctx.Offices on d.Id equals o.DepartmentId
                 outer left join e in ctx.Employees on o.Id equals e.OfficeId
                 group e by d into de
                 select new {
                    DepartmentId = de.Key.Id,
                    AverageAge = de.Count() == 0 ? 0 : de.Average(e => e.Age),
                 };
Run Code Online (Sandbox Code Playgroud)

变成:

var newQ2 = from d in ctx.Departments
                     join o in ctx.Offices on d.Id equals o.DepartmentId
                     join e in ctx.Employees on o.Id equals e.OfficeId
                     group e by d into de.DefaultIfEmpty()
                     select new {
                        DepartmentId = de.Key.Id,
                        DepartdentName = select d.Name from d where d.id = de.Key.Id,
                        AverageAge = de.Count() == 0 ? 0 : de.Average(e => e.Age),
                     };
Run Code Online (Sandbox Code Playgroud)

附录:我会使用一个子选项来匹配额外的名称,不知道你的代码中我即兴创建的数据库布局,但你可以使它更高效,并且还有基于子选择的多部分连接.对不起,我不能在工作中测试这个代码,我可以很好地估计,但如果你需要更详细的答案,需要更多关于你的部门名称所在位置的信息:)我已经将左外连接更改回连接,抱歉我忘记在c#中使用linq你可以使用DefaultIfEmpty()在代码中引起外部左连接行为.

外部左连接将返回没有相应值的空值,但允许返回具有相应值的任何部分.然而,加入不会返回任何空条目,我怀疑这是为什么你有两个查询?

我提出的查询的唯一警告是,如果它们是空值,您将需要在使用之前填充所需的任何值,例如,如果DE为null,则DepartmentId将需要一些逻辑来填充它.

  • 外左连接是一个很好的解决方案.但是它不是有效的linq语法,如果语法有效,则3个单词将为蓝色作为c#关键字. (2认同)