简体   繁体   English

LINQ 查询:具有另一个表的 Count 元素的新查询对象

[英]LINQ Query: new query object with a Count element of another table

Bellow is the LINQ query I am trying to operate波纹管是我试图操作的 LINQ 查询

var custSelect = from m in _context.Entities
                         where m.Active == true && m.EntityTypeId == 1
                         orderby m.Name
                         select new { m.EntityId, m.Name, JobCount = _context.Jobs.Where(o => o.CustomerId == m.EntityId).Distinct().ToList().Count };

I want to be able to select a new selection variable as JobCount which is an integer counting how many jobs are attached to said customer.我希望能够选择一个新的选择变量作为 JobCount,它是一个整数,计算附加到所述客户的作业数量。 Then later, during the model creation, I want to be able to then order by the Count variable for example.然后,在模型创建过程中,我希望能够通过 Count 变量进行排序。

Is there any way to do this?有没有办法做到这一点?

You can try this way, Here is the live demo您可以尝试这种方式,是现场演示

var result = (from e in entities
                  join j in jobs on e.EntityId equals j.CustomerId
                  where e.Active && e.EntityTypeId == 1
                  select new 
                  {
                      e.EntityId, 
                      e.Name,
                      j.JobId
                  }).GroupBy( p => new { p.EntityId, p.Name })
                    .Select(g => new 
                                {
                                    EntityId = g.First().EntityId, 
                                    Name = g.First().Name,
                                    JobCount = g.Count()  
                                })
                    .OrderBy(p => p.Name);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM