dotnet / dotnet/efcore

Sql Server - LINQ Contains returns false positive results for string values larger than column size

Open
#32,735 5 comments 2 reactions 1 assignee Claimed by @AndriySvyryd View on GitHub
area-primitive-collections area-query customer-reported regression
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

We've upgraded to EF Core 8.0.0 (from 7.0.8) and have started experiencing an issue with `Contains` in LINQ queries. This seems to be related to the [breaking change described here](https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-8.0/breaking-changes#sqlserver-contains-compatibility). Currently it looks like the query ends up casting string values within `OPENJSON` to `nvarchar(COLUMN-SIZE)` which can result in false positive results for values larger than the column size.

For example, suppose we have a table the following record where Code is an `nvarchar(2)` column:

| Id (int) | Code (nvarchar(2)) |
|----------|--------------------|
| 1 | IN |

```csharp
class SampleItem
{
int Id { get; set; }
string Code { get; set; }
}

var valuesToCheck = new [] { "INVALID" };

var items = dbContext.Set()
.Where(i => valuesToCheck.Contains(i.Code))
.ToList();
```

The query generates the following SQL:
```sql
exec sp_executesql N'SELECT [s].[Id], [s].[Code]
FROM [SampleItems] AS [s]
WHERE [s].[Code] IN (
SELECT [c].[value]
FROM OPENJSON(@__codes_0) WITH ([value] nvarchar(2) ''$'') AS [c]
)',N'@__codes_0 nvarchar(4000)',@__codes_0=N'["INVALID"]'
```

Since `[value]` is truncated to 2 characters, `INVALID` is becomes `IN` which is in the table, resulting in a false positive result.

[Sample Code w/ Issue](https://github.com/dotnet/efcore/files/13846782/EfContainsIssue.zip)

EF Core version: 8.0.0
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: .NET 8.0
Operating system: Windows 11 Pro 22H2
IDE: Visual Studio 2022 17.8.3

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.