2010-12-23 148 views

回答

3

想想它在零件...

你會如何做到這一點在SQL?

SELECT DISTINCT sc.CategoryID 
FROM SubCategory sc 
WHERE sc.SubCategory IN (
    SELEcT DISTINCT scpg.SubCategoryID 
    FROM SubCategoryProductGroups scpg 
    WHERE scpg.ProductGroupID = 12) 

要LINQ2SQL做到這一點會是這樣的......

using (var db = new MyDataContext()) { 
    var query = (from sc in db.SubCategories 
       where (from scpg in db.SubCategoryProductGroups 
         where scpg.ProductGroupID == 12 
         select scgp.SubCategoryID).Distinct().Contains(sc.SubCategoryID) 
       select sc.CategoryID).Distinct(); 
} 

...你也可以使用加入...

SQL ...

SELECT DISTINCT sc.CategoryID 
FROM SubCategory sc 
JOIN SubCategoryProductGroups scpg ON sc.SubCategoryID = scpg.SubCategoryID 
WHERE scpg.ProductGroupID = 12 

LINQ2SQL ...

var query = (from sc in db.SubCategories 
      join scpg in db.SubCategoryProductGroups 
        on sc.SubCategoryID equals scpg.SubCategoryID 
      where scpg.ProductGroupID == 12 
      select sc.CategoryID).Distinct(); 

...如果你LINQ模型你也許可以做到這一點的關係,知道...

var query = (from sc in db.SubCategories 
      where sc.SubCategoryProductGroups 
        .Any(s=>s.ProductGroupID == 12) 
      select sc.CategoryID).Distinct(); 
+0

完美,謝謝你的許多例子。 – 2010-12-23 03:11:56

0

希望這有助於

var result = from sc in SubCategory 
    join scpg in SubCategoryProductGroups 
    on sc.SubCategoryID equals scpg.SubCategoryID 
    where scpg.ProductsGroupID =12 
    select sc.CategoryID 
1

dc.subcatogorysproductsgroups.where(O => 0 .productgroupid == 12).select(j => o.subcatogory.catogory);

有一件事是如果你使用linq到sql那麼沒有必要使用連接,如果數據庫如果完全規範化。 並在使用此代碼之前,請確保將dc.defferedloadingenabled設置爲true。 或使用DataLoadOptions和Dc.loadPropery