4

我有以下 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]

提前致谢

4

1 回答 1

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());
于 2012-04-06T17:37:25.040 回答