tags:

views:

120

answers:

2

Hi there,

Am new to this here is my T-SQL

SELECT category.id, category.name,COUNT(job.id) AS countofjobs 
FROM category 
LEFT OUTER JOIN job ON category.id = job.categoryid AND job.active=1 
WHERE category.featured=1 
GROUP BY category.id, category.name
ORDER BY category.name

what will be the equivalent LINQ to SQL code? any help will be appreciated

Sorry I forgot to mention that there is no relationship database side, tables have no association at all defined in db, thats the main issue, this is really just sample sql to see how I can write Link to SQL for T-SQL that requires: Left outer join, Count of outer join table records and sorting

+5  A: 
var result = dataContext.Categories
                  .Where(c => c.Featured)
                  .OrderBy(c => c.Name)
                  .Select(c => new { c.Id, 
                                     c.Name, 
                                     CountOfJobs = c.Jobs.Count(j => j.Active) };

Alternatively:

var result = from c in dataContext.Categories
             where c.Featured
             orderby c.Name
             select new { c.Id, c.Name, CountOfJobs = c.Jobs.Count(j => j.Active) };
Mehrdad Afshari
Too old to change vote? Wha? This answer is wrong now that the questioner has stated he has no associations in his dbml.
jfar
@jfar: I prefer to leave the answer as it is for future users who might come up with a similar question, since there's another answer that covers the other case. And by the way, I don't think answers that are rendered obsolete by a question edit should be downvoted. They were correct enough at the time they've answered.
Mehrdad Afshari
Leaving the answer is fine but it shouldn't be #1, my vote would have helped to change that and get the correct answer on top.
jfar
jfar: I agree. But "accepting an answer" is designed to handle that case, not votes.
Mehrdad Afshari
+1  A: 

Since you don't have relationships:

var result = from c in dataContext.Categories
             where c.Featured
             orderby c.Name
             select new {
                 c.Id,
                 c.Name,
                 CountOfJobs = dataContext.Jobs.Count(j => j.categoryId == c.Id && j.Active)
             };
John Gietzen