Select projection can create a single instance of a member class in multiple main objects
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
#7983
@smitpatel Is this a duplicate of #7983? If so, does this mean that the behavior in 2.2 was wrong, or just client evaluated? Is this the behavior now fixed or not supported?
Answer to all the questions above is no. Though it has similarities with the linked issue. We need to discuss as a team what behaviour we want.
@JimLynn We are curious why you want to return a value in a query that is then immediately overwritten in a foreach loop?
@ajcvickers I didn't really, but this was an old bit of code that had been refactored to do just that, so I was worried that this might be a pattern that pops up in other old code. The fact that this doesn't behave in a way that you would expect C# code to behave felt wrong, hence the bug report.
Once I realised what was happening, I refactored again to remove this particular select clause, so it's not like it's it's a killer bug. It just freaked me out.