LINQ和参考列表问题

时间:2012-04-06 17:33:08

标签: c# linq linq-to-sql

我有以下代码与LINQ

var q = (from web in DataContext.Webs select web);
List<int?> k1 = new List<int?>() { 1, 2 };
List<int?> k2=new List<int?>() { 16, 17 };
            q = q.Where(web => DataContext.WebTechMaps.Any(t => t.WebsiteId == web.WebsiteId && k1.Contains(t.TechId)));
            System.Diagnostics.Debug.WriteLine(q.Count());
            k1 = k2;
            q = q.Where(web => DataContext.WebTechMaps.Any(t => t.WebsiteId == web.WebsiteId && k1.Contains(t.TechId)));
            System.Diagnostics.Debug.WriteLine(q.Count());

这是它生成的查询。

首次执行计数。

SELECT COUNT(*) AS [value]
FROM [dbo].[Web] AS [t0]
WHERE EXISTS(
    SELECT NULL AS [EMPTY]
    FROM [dbo].[WebTechMap] AS [t1]
    WHERE ([t1].[WebsiteId] = ([t0].[WebsiteId])) AND ([t1].[TechId] IN (@p0, @p1))
    )
-- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [1]
-- @p1: Input Int (Size = -1; Prec = 0; Scale = 0) [2]

计数功能的第二次执行

SELECT COUNT(*) AS [value]
FROM [dbo].[Web] AS [t0]
WHERE (EXISTS(
    SELECT NULL AS [EMPTY]
    FROM [dbo].[WebTechMap] AS [t1]
    WHERE ([t1].[WebsiteId] = ([t0].[WebsiteId])) AND ([t1].[TechId] IN (@p0, @p1))
    )) AND (EXISTS(
    SELECT NULL AS [EMPTY]
    FROM [dbo].[WebTechMap] AS [t2]
    WHERE ([t2].[WebsiteId] = ([t0].[WebsiteId])) AND ([t2].[TechId] IN (@p2, @p3))
    ))
-- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [16]
-- @p1: Input Int (Size = -1; Prec = 0; Scale = 0) [17]
-- @p2: Input Int (Size = -1; Prec = 0; Scale = 0) [16]
-- @p3: Input Int (Size = -1; Prec = 0; Scale = 0) [17]

请查看传递给查询的参数。

似乎它使用两个表达式的新引用对象。

不知何故@ p0和@ p1改变了他们的旧值。 我理解Linq中的问题是它使用了新引用的对象。

-- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [1]
-- @p1: Input Int (Size = -1; Prec = 0; Scale = 0) [2]



-- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [16]
-- @p1: Input Int (Size = -1; Prec = 0; Scale = 0) [17]
-- @p2: Input Int (Size = -1; Prec = 0; Scale = 0) [16]
-- @p3: Input Int (Size = -1; Prec = 0; Scale = 0) [17]

有人可以解释如何使用List对象的相同名称,但使用正确的List

保持查询

所需的输出

-- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [1]
-- @p1: Input Int (Size = -1; Prec = 0; Scale = 0) [2]
-- @p2: Input Int (Size = -1; Prec = 0; Scale = 0) [16]
-- @p3: Input Int (Size = -1; Prec = 0; Scale = 0) [17]

先谢谢

1 个答案:

答案 0 :(得分:4)

您的第一个查询表达式使用k1。它使用变量 kl,这就是捕获的内容。当您更改k1的值时,这会有效地更改查询的含义。如果您不希望更改查询的含义,请不要更改捕获的变量!只需在第二个过滤器中使用k2

var q = (from web in DataContext.Webs select web);
List<int?> k1 = new List<int?>() { 1, 2 };
List<int?> k2=new List<int?>() { 16, 17 };
q = q.Where(web => DataContext.WebTechMaps
                              .Any(t => t.WebsiteId == web.WebsiteId && 
                                        k1.Contains(t.TechId)));
System.Diagnostics.Debug.WriteLine(q.Count());
q = q.Where(web => DataContext.WebTechMaps
                              .Any(t => t.WebsiteId == web.WebsiteId &&
                                   k2.Contains(t.TechId)));
System.Diagnostics.Debug.WriteLine(q.Count());