Skip to content

Duplicate identical SQL parameters with set operations #38068

@bedpans

Description

@bedpans

Bug description

The following code outputs SQL query with two parameters whose values are identical. Query itself doesn't make sense, but it demonstrates the issue.

Code:

var query1 = dbContext.Products.Where(x => storeIds.Contains(x.StoreId)).Select(x => x.ProductId);
var query2 = dbContext.Employees.Where(x => storeIds.Contains(x.StoreId)).Select(x => x.EmployeeId);
var query3 = query1.Union(query2);
Console.WriteLine(query3.ToQueryString());

Output:

DECLARE @storeIds1 uniqueIdentifier = '4a3aa2fa-deec-4880-91de-0bfe05d9c272';
DECLARE @storeIds2 uniqueIdentifier = '4a3aa2fa-deec-4880-91de-0bfe05d9c272';

SELECT [p].[product_id]
FROM [products] AS [p]
WHERE [p].[store_id] = @storeIds1
UNION
SELECT [e].[employee_id] AS [product_id]
FROM [employees] AS [e]
WHERE [e].[store_id] = @storeIds2

This by itself might be not a big issue, however I have noticed that removing and/or adding navigation properties can eliminate duplicate parameter resulting in a query like this:

DECLARE @storeIds1 uniqueIdentifier = 'c2232ea2-24b4-4be5-8d63-1d0425d8f435';

SELECT [p].[product_id]
FROM [products] AS [p]
WHERE [p].[store_id] = @storeIds1
UNION
SELECT [e].[employee_id] AS [product_id]
FROM [employees] AS [e]
WHERE [e].[store_id] = @storeIds1

This problem wasn't trivial to repeat for me, so I prepared a Visual Studio project where issue can be reproduced:
Solution1.zip

This also happens on EF Core 8 and EF Core 9, although queries are slightly different.

If this behavior is intentional could you provide an explanation why this is happening?

Your code

Solution1.zip

Stack traces


Verbose output


EF Core version

10.0.5

Database provider

Microsoft.EntityFrameworkCore.SqlServer

Target framework

.NET 10.0

Operating system

Windows 11

IDE

Visual Studio 2026 18.4.3

Metadata

Metadata

Assignees

No one assigned

    Type

    No fields configured for Bug.

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions