帮助多表linq查询

时间:2010-12-23 02:13:56

标签: c# linq-to-sql

我有一个像这样设置的数据库: alt text

假设我有一个id为12的产品组。如何获得此特定产品组的CategoryID?我必须加入吗?

3 个答案:

答案 0 :(得分: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();

答案 1 :(得分:1)

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

有一件事是如果你使用linq到sql那么如果数据库完全正常化则不需要使用join。 在使用此代码之前,请确保将dc.defferedloadingenabled设置为true。  或使用DataLoadOptions和Dc.loadPropery

答案 2 :(得分:0)

希望这有帮助

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