dotnet / dotnet/efcore

Select projection can create a single instance of a member class in multiple main objects

Open
#29,436 5 comments 0 reactions 0 assignees View on GitHub
area-query customer-reported needs-design
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

This is a bug in EF Core 6.0.10 which didn't seem to happen in EF core 2.2. I found it upgrading an older project.

What my code was doing was a query for a set of dealers, then in the Select clause creating a compound object where one property is the dealer object from the query, and the other object is a new instance of a data object.

If the Data object is initialised with the default constructor, or if any of its properties are initialised with constants, or data from the query, everything is fine.

However, in the specific case where the Data object has one property initialised from a variable outside the scope of the Select clause (and therefore a captured variable), only one instance of the Data class is created, and that same instance is used for all the compound objects returned by the query. This is not the expected behaviour.

Here's a repo with a simple demonstration of the issue. https://github.com/JimLynn/EfConstantObjectBug6

The sample shows a query that works properly, and one which demonstrates this issue. You'll need to edit the connection string to point to a SQL Server instance that works for you.

EF Core version: 6.0.10
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: .NET 6.0
Operating system: Windows 10
IDE: Visual Studio 2022 17.3.5

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.