标签:
接触 LINQ 也有很长的一段时间了,有些在 SQL 语句中用的很顺手的东西在 Linq 中却不知道如何实现了,最近遇到了一个问题,在 LINQ 的 Where 条件式中要如何使用 IN 与 NOT IN 呢? 这时候真的开始怀念 T-SQL 其实还是最好用的。为了让自己日后开发时更为方便,于是花了一点时间,参考一些网络资料及 MSDN 后,得到以下的测试結果:
T-SQL的IN:
Select
ProductID, ProductName, CategoryID
From
dbo.Products
Where
CategoryID
in
(1, 2)
T-SQL的NOT IN:
Select
ProductID, ProductName, CategoryID
From
dbo.Products
Where
CategoryID
not in
(1, 2)
Or
Select
ProductID, ProductName, CategoryID
From
dbo.Products
Where
not
CategoryID
in
(1, 2)
LINQ的IN:
var queryResult = from p
in
db.Products
where (
new int
?[] {1,2}).Contains(p.CategoryID)
select p;
LINQ的IN解析成SQL:
SELECT
[t0].[ProductID], [t0].[ProductName], [t0].[SupplierID], [t0].[CategoryID], [t0].[QuantityPerUnit], [t0].[UnitPrice], [t0].[UnitsInStock], [t0].[UnitsOnOrder], [t0].[ReorderLevel], [t0].[Discontinued]
FROM
[dbo].[Products]
AS
[t0]
WHERE
[t0].[CategoryID]
IN
(@p0, @p1)
LINQ的NOT IN:
var queryResult = from p
in
db.Products
where ! (
new int
?[] {1,2}).Contains(p.CategoryID)
select p;
LINQ的NOT IN解析成SQL:
SELECT
[t0].[ProductID], [t0].[ProductName], [t0].[SupplierID], [t0].[CategoryID], [t0].[QuantityPerUnit], [t0].[UnitPrice], [t0].[UnitsInStock], [t0].[UnitsOnOrder], [t0].[ReorderLevel], [t0].[Discontinued]
FROM
[dbo].[Products]
AS
[t0]
WHERE
NOT
[t0].[CategoryID]
IN
(@p0, @p1)
标签:
原文地址:http://www.cnblogs.com/ajunForNet/p/4378684.html