Skip to content

Using NpgsqlParameter in SqlQuery can generate invalid query if parameter is referenced multiple times in v10 #3703

@BladeWise

Description

@BladeWise

Attempting to use NpgsqlParameter with SqlQuery explicitly in v10 can generate invalid queries if the same parameter instance is referenced multiple times.
The same issue does not occur using v9.

Consider the following example:

var v = new NpgsqlParameter<int>("value", 1);
var values = await dbContext.Database.SqlQuery<int>($"""
                                                     SELECT 1
                                                     WHERE {v} >= 0 OR {v} <= 0
                                                     """).ToListAsync();

where we want to ensure parameter value is provided once and used two times in the query.

Using Npgsql.EntityFrameworkCore.PostgreSQL 10.0.0 the generated log is the following

Microsoft.EntityFrameworkCore.Database.Command: Error: Failed executing DbCommand (628ms) [Parameters=[value0='1'], CommandType='Text', CommandTimeout='30']
SELECT 1
WHERE @value >= 0 OR @value0 <= 0

as you can see, a single parameter is emitted for the command (value0), but produced SQL still references two different parameters.

The same code using Npgsql.EntityFrameworkCore.PostgreSQL 9.0.4 generates the following log

Microsoft.EntityFrameworkCore.Database.Command: Information: Executed DbCommand (22ms) [Parameters=[value='1'], CommandType='Text', CommandTimeout='30']
SELECT 1
WHERE @value >= 0 OR @value <= 0

where a single parameter is provided and the same placeholder is used twice.

It seems both v9 and v10 recognize the parameter instance as unique and provide a single parameter to the SQL command, but v10 does not use the same placeholder for each usage.

A full repro is available to verify the above behavior.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions