How would you convert this SQL statement to LINQ, most efficient ?
SELECT categoryName,
(SELECT COUNT(*) cnt
FROM itemCategories
WHERE (categories.categoryId = itemCategories.categoryId)
AND (Items.countryPartId = 1)) AS cnt
FROM categories, Items
This is the LINQ query I’ve got right now:
var q =
from c in context.categories
select new CategoryCount
{
CategoryName = c.categoryName,
Counter = (
from i in context.itemCategories
where c.categoryId == i.categoryId
select i).Count()
};
This should produce the exact same query (excluding the seemingly unnecessary use of the
Itemstable) and is much more natural to me IMHO.If the join makes you queasy for whatever reason, here’s an alternative.