2010-12-06 68 views
0

如何將此SQL語句轉換爲LINQ,效率最高?此SQL到LINQ

SELECT categoryName, 
     (SELECT COUNT(*) cnt 
     FROM itemCategories 
     WHERE (categories.categoryId = itemCategories.categoryId) 
      AND (Items.countryPartId = 1)) AS cnt 
    FROM categories, Items 

這是LINQ查詢我有現在:

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() 
    }; 
+0

這是LINQ子句而不與WHERE子句中: VAR Q =(從C中context.categories \t選擇新CategoryCount \t { \t類別名稱= c.categoryName, 計數器= (from i in context.itemCategories where c.categoryId == i.categoryId select i).Count() }); – danielovich 2010-12-06 12:03:33

回答

2

這應該產生完全相同的查詢(不包括看似不必要的使用Items表),是恕我直言,更自然的我。

var query = from c in context.categories 
      join ic in context.itemCategories 
       on c.categoryId equals ic.categoryId into joined 
      select new CategoryCount 
      { 
       CategoryName = c.categoryName, 
       Counter = joined.Count(), 
      }; 

如果加入讓你因任何原因而陷入que,,這裏有一個選擇。

var query = from c in context.categories 
      select new CategoryCount 
      { 
       CategoryName = c.categoryName, 
       Counter = context.itemCategories 
           .Where(ic => ic.categoryId == c.categoryId) 
           .Count(), 
      }; 
0

我想我自己。很抱歉造成您的不便史蒂芬,就不會再發生了:)

var q = (from c in context.categories 
     from it in context.Items 
     select new CategoryCount 
     { 
      CategoryName = c.categoryName, 
      Counter = (from i in context.itemCategories 
        where c.categoryId == i.categoryId && it.countryPartId == 1 select i).Count() 
     });