在排除错误时,我遇到了这个问题。这似乎是由于延迟执行和查询使用变量关键字的最后一个值。解决此问题的推荐模式是什么。
var query = from c in dbContext.Cars
select c;
var keywords = new string[] { "Clean", "Car" };
foreach (var keyword in keywords)
{
query = query.Where(c => c.Name.Contains(keyword));
}
var cars = query.ToList();
结果是这样的查询(注意两个参数的值都是“汽车”)
exec sp_executesql N'SELECT
[Extent1].[CarID] AS [MID],
[Extent1].[Name] AS [Name],
FROM [dbo].[Cars] AS [Extent1]
WHERE ([Extent1].[Name] LIKE @p__linq__0 ESCAPE N''~'') AND ([Extent1].[Name] LIKE @p__linq__1 ESCAPE N''~'')
',N'@p__linq__0 nvarchar(4000),@p__linq__1 nvarchar(4000)',@p__linq__0=N'%Car%',@p__linq__1=N'%Car%'
LINQPad 中的调试也显示相同的查询
DECLARE p__linq__0 NVarChar(1) = '%Car%'
DECLARE p__linq__1 NVarChar(1) = '%Car%'
SELECT
[Extent1].[CarID] AS [MID],
[Extent1].[Name] AS [Name],
FROM [dbo].[Cars] AS [Extent1]
WHERE ([Extent1].[Name] LIKE @p__linq__0 ESCAPE N'~') AND ([Extent1].[Name] LIKE @p__linq__1 ESCAPE N'~')