tags:

views:

54

answers:

1

What would be the Linq equivalent of the following TSQL query:

SELECT c.[CustomerId]
  ,c.[Name]
  , (SELECT COUNT(*) FROM Incidents WHERE CustomerId = c.CustomerId) AS IncidentsCount
  , (SELECT COUNT(*) FROM Opportunities WHERE CustomerId = c.CustomerId) AS OpportunitiesCount
  , (SELECT COUNT(*) FROM Visits WHERE CustomerId = c.CustomerId) AS VisitsCount

FROM [Customers] c

+3  A: 

I haven't double-checked this in visual studio but this should work:

var x = (from c in Context.Customers
         select new {
             CustomerId = c.CustomerId,
             Name = c.Name,
             IncidentsCount = 
                 Context.Customers.Count(i => i.CustomerId == c.CustomerId),
             OpportunitiesCount = 
                 Context.Opportunities.Count(o => o.CustomerId == c.CustomerId),
             VisitsCount = 
                 Context.Visits.Count(v => v.CustomerId == c.CustomerId)
         });

Update: I changed the code to be a little bit easier to read.

Jared
Excellent, thank you!