0

I have the following:

        var result = this._context.Clients.Join(this._context.Jobs, c => c.Id, j => j.Id, (c, j) =>
            new ClientIndexDto
            {
                Id = c.Id,
                ClientNo = c.ClientNo,
                Active = c.Active,
                ClientFirstName = c.ClientFirstName,
                ClientLastName = c.ClientLastName,
                Company = c.Company,
                CompanyName = c.CompanyName,
                MobilePhone = c.MobilePhone,
                IsWarrantyCompany = c.IsWarrantyCompany,
                JobsCount = ???

            });

I would like to get the number of jobs a client has.. is there a way to do this?

Hadi Samadzad
  • 1,480
  • 2
  • 13
  • 22
si2030
  • 3,895
  • 8
  • 38
  • 87
  • it sounds like [this group by / join answer](https://stackoverflow.com/a/9173783/5174469) might help you – Mong Zhu Apr 27 '20 at 13:51
  • You can use [groupJoin](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.groupjoin?view=netcore-3.1) Instead ``Join`` – Mohammed Sajid Apr 27 '20 at 14:05

2 Answers2

0

As suggested by Zhu and Sajid, GroupJoin should work:

var result = this._context.Clients.GroupJoin(this._context.Jobs, c => c.Id, j => j.Id, (c, j) =>
        new ClientIndexDto {
           Id = c.Id,
           ClientNo = c.ClientNo,
           Active = c.Active,
           ClientFirstName = c.ClientFirstName,
           ClientLastName = c.ClientLastName,
           Company = c.Company,
           CompanyName = c.CompanyName,
           MobilePhone = c.MobilePhone,
           IsWarrantyCompany = c.IsWarrantyCompany,
           JobsCount = j.Count()
        });
Raju Joseph
  • 493
  • 1
  • 6
  • 13
0

You can also try this code:

 var result = (from b in _context.Clients.ToList()
                      join a in _context.Jobs.ToList() on b.Id equals a.Id
                      group a by b into g
                      select new ClientIndexDto
                      {
                          Id = g.Key.Id,
                          ClientNo = g.Key.ClientNo,
                          Active = g.Key.Active,
                          ClientFirstName = g.Key.ClientFirstName,
                          ClientLastName = g.Key.ClientLastName,
                          Company = g.Key.Company,
                          CompanyName = g.Key.CompanyName,
                          MobilePhone = g.Key.MobilePhone,
                          IsWarrantyCompany = g.Key.IsWarrantyCompany,
                          JobsCount = g.Count()
                      });
LouraQ
  • 6,443
  • 2
  • 6
  • 16