几种常见复合sql查询语句的linq写法[继续补充中]
1.IN 语句
尝试了很多次,好象linq死活不生成in语句,无奈只能做了下变换
例,要找出"手机大类"以及"手机下属所有子类"的产品 (手机大类的ID为D0C37275-2279-4590-A679-C65A4F28918F)
select F_ID,F_Name,F_CLsID From T_Product Where F_ClsID in (
Select F_ID From T_Class Where F_ID='D0C37275-2279-4590-A679-C65A4F28918F' OR F_ParentIdStr like '%D0C37275-2279-4590-A679-C65A4F28918F%')
Select F_ID From T_Class Where F_ID='D0C37275-2279-4590-A679-C65A4F28918F' OR F_ParentIdStr like '%D0C37275-2279-4590-A679-C65A4F28918F%')
效果上等效于
Select P.F_ID,P.F_Name,P.F_ClsID From T_Product As P Inner Join T_Class As C On C.F_ID = P.F_CLSID where
C.F_ID='D0C37275-2279-4590-A679-C65A4F28918F' OR C.F_ParentIdStr like '%D0C37275-2279-4590-A679-C65A4F28918F%'
C.F_ID='D0C37275-2279-4590-A679-C65A4F28918F' OR C.F_ParentIdStr like '%D0C37275-2279-4590-A679-C65A4F28918F%'
或
Select P.F_ID,P.F_Name,P.F_ClsID From T_Product As P,T_Class As C where
P.F_ClSID = C.F_ID And (
C.F_ID='D0C37275-2279-4590-A679-C65A4F28918F' OR
C.F_ParentIdStr like '%D0C37275-2279-4590-A679-C65A4F28918F%')
P.F_ClSID = C.F_ID And (
C.F_ID='D0C37275-2279-4590-A679-C65A4F28918F' OR
C.F_ParentIdStr like '%D0C37275-2279-4590-A679-C65A4F28918F%')
linq to sql的等效写法:
var query = from p in db.T_Products join
c in db.T_Classes on p.F_CLSID equals c.F_ID
where c.F_ID == new Guid("D0C37275-2279-4590-A679-C65A4F28918F") || c.F_ParentIDStr.Contains("D0C37275-2279-4590-A679-C65A4F28918F")
select new { p.F_ID, p.F_Name };
c in db.T_Classes on p.F_CLSID equals c.F_ID
where c.F_ID == new Guid("D0C37275-2279-4590-A679-C65A4F28918F") || c.F_ParentIDStr.Contains("D0C37275-2279-4590-A679-C65A4F28918F")
select new { p.F_ID, p.F_Name };
或
var query = from p in db.T_Products
from c in db.T_Classes
where p.F_CLSID == c.F_ID && (c.F_ID == new Guid("D0C37275-2279-4590-A679-C65A4F28918F") || c.F_ParentIDStr.Contains("D0C37275-2279-4590-A679-C65A4F28918F"))
select new { p.F_ID, p.F_Name };
from c in db.T_Classes
where p.F_CLSID == c.F_ID && (c.F_ID == new Guid("D0C37275-2279-4590-A679-C65A4F28918F") || c.F_ParentIDStr.Contains("D0C37275-2279-4590-A679-C65A4F28918F"))
select new { p.F_ID, p.F_Name };
作者:菩提树下的杨过
出处:http://yjmyzz.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://yjmyzz.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。