Okay, this behavior has me really stumped. I have an IQueryable list that I’m trying to add Where clauses to check whether a string field contains a substring. When I hardcode the search string like this:
sourceList = sourceList.Where(license => license.FileNumber.Contains("S0"))
it works as expected and generates the internal query from inspecting sourceList in the Visual Studio debugger:
{SELECT [Extent1].[id] AS [id], [Extent1].[FileNumber] AS [FileNumber],
[Extent1].[LegalLocation] AS [LegalLocation]FROM [dbo].[Licenses]
AS [Extent1]WHERE [Extent1].[FileNumber] LIKE N'%S0%'}
The strange thing happens when I set the search value from a variable like:
string testString = "S0";
sourceList = sourceList.Where(license => license.FileNumber.Contains(testString))
This generates the internal query:
{SELECT [Extent1].[id] AS [id], [Extent1].[FileNumber] AS [FileNumber],
[Extent1].[LegalLocation] AS [LegalLocation]FROM [dbo].[Licenses]
AS [Extent1]WHERE [Extent1].[FileNumber] LIKE @p__linq__0 ESCAPE N'~'}
Notice the difference in the LIKE part at the end? I am really confused. Any help would be greatly appreciated. Here’s hoping it’s something really stupid. In case it has any relevance, this is for filtering data from an Entity Framework source.
Thanks,
Jason
If you observe the actual query, you’ll see
@p__linq__0is actually assigned theS0value, then passed to the query.Which basically is like:
And because it’s a parameter, LINQ just takes the precaution and adds the
ESCAPEclause. It’s also a variable instead of a hard-coded constant and any changing value in a LINQ statement is passed as a parameter instead of inserted directly in to the query.Reference: LIKE (Transact-SQL)