Repository navigation
Description
I wrote two manual SQL queries with parameters with the same names but with different values like this:
var result = await Enumerable
.Range(1, 2)
.Select(index => dbContext
.Set<TestEntity>()
.FromSqlRaw(
"SELECT @date AS Date",
new SqlParameter("date", new DateOnly(2024, 1, index))))
.Aggregate(Queryable.Union)
.ToListAsync();
foreach (var line in result)
{
Console.WriteLine(line.Date);
}
I expected to get two results with 2024-01-01 and 2024-01-02 but got only the result 2024-01-01.
However, this works as expected:
var result = await Enumerable
.Range(1, 2)
.Select(index => dbContext
.Set<TestEntity>()
.FromSqlRaw(
"SELECT {0} AS Date",
new DateOnly(2024, 1, index)))
.Aggregate(Queryable.Union)
.ToListAsync();
foreach (var line in result)
{
Console.WriteLine(line.Date);
}
I have created an example project showcasing the bug: https://github.com/samuel-utbult-oborgen/ef-core-bug
I suspect this could be because the variable "date" is created for the combined query and its value is set to 2024-01-01 while the value 2024-01-02 is ignored. The parameters should reasonably be isolated between the queries as they are specified for each query respectively.
EF Core version: 8.0.1
Database provider: (e.g. Microsoft.EntityFrameworkCore.SqlServer)
Target framework: (e.g. .NET 8.0)
Operating system: macOS Sonoma 14.2.1
Activity
roji commentedon Jan 26, 2024
Regardless of the actual issue above, be aware that this code executes a separate query for each value in the range, doing many sequential roundtrips, which is slow. Instead, consider just creating an array of your DateTimes and doing a single query with Contains over that array.
samuel-utbult-oborgen commentedon Jan 29, 2024
The provided example is the most simple one I could come up with that showcases the bug. The production code where this bug was found is considerably more complicated and there is an actual reason why such an SQL parameter is useful in that case.
ajcvickers commentedon Feb 1, 2024
Debug query output for the first case, which ultimately returns one result. (Note that the database contains no data.)
Debug query output for the second case, which ultimately returns two results. (Note that the database contains no data here either.)
samuel-utbult-oborgen commentedon Feb 1, 2024
A clear observation to make in the debug output is that one parameter
dateexists in the first query but two parametersp0andp1exists in the second query. This conforms to my speculation above. EF Core knows how to separate between{0}yet it does not know how to separate between@date. I hope this provides enough information for the developers of EF Core to know how this bug could be fixed.Throw when same-named DbParameters are hard-coded in FromSql/SqlQuery…
Throw when same-named DbParameters are hard-coded in FromSql/SqlQuery…
Throw when same-named DbParameters are hard-coded in FromSql/SqlQuery…