Aquaphor
Aquaphor

Reputation: 158

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

Bellow is the LINQ query I am trying to operate

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. Then later, during the model creation, I want to be able to then order by the Count variable for example.

Is there any way to do this?

Upvotes: 1

Views: 305

Answers (1)

Nguyễn Văn Phong
Nguyễn Văn Phong

Reputation: 14218

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);

Upvotes: 1

Related Questions