我在我的Entity Framework repo上创建了这个搜索方法:
public IEnumerable<Person> GetPersonsWithFilter(string filter)
{
var items =
filter.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var query = _personRepo.All(); // Return IQueryable<Person>
foreach (var item in items)
{
query = query.Where(i => i.SearchName.Contains(item.ToLower()));
}
query.TraceSql(i => Logger.Error(i));
return query.Take(50);
}
TraceSql输出生成的sql。如果我的过滤器是“John Landheer”,则正确生成sql:
SELECT [Extent1].[PersonId] AS [PersonId] // Other fields deleted for readability
FROM [dbo].[Person] AS [Extent1]
WHERE
(( CAST(CHARINDEX(LOWER(@p__linq__0), [Extent1].[SearchName]) AS int)) > 0)
AND
(( CAST(CHARINDEX(LOWER(@p__linq__1), [Extent1].[SearchName]) AS int)) > 0)
但是,参数是相同的:@p_ linq _0 ='landheer'和@p_ linq _1 ='landheer'
现在,如果我将循环更改为:
foreach (var item in items)
{
var tempItem = item;
query = query.Where(i => i.SearchName.Contains(tempItem.ToLower()));
}
一切正常吗?!?!
我认为它与EF构建表达式树的方式有关,但它看起来有点出乎意料。任何人都可以对此有所了解吗?
约翰
答案 0 :(得分:0)
感谢Equiso,我没有找到您提到的问题。所以这与Linq query built in foreach loop always takes parameter value from last iteration完全相同。