使用PostgreSQL数据库和Dapper。
这是一个失败的代码的最小例子。
await using var connection = new NpgsqlConnection(_configuration.ConnectionString);
return await connection.QueryAsync<Diamond>(
@"SELECT
id,
name
FROM
product
WHERE
@Names IS NULL OR name = ANY(@Names);",
new
{
Names = Names,
});
如果 Names = new { "Tom", "Dick", "Harry" }
.
然而,它失败了,如果 Names = (string[]) null
.
我得到的错误是
Npgsql.PostgresException (0x80004005): 42P18: could not determine data type of parameter $1
at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<<DoReadMessage>g__ReadMessageLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<<DoReadMessage>g__ReadMessageLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming)
at Npgsql.NpgsqlCommand.ExecuteReaderAsync(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
at Npgsql.NpgsqlCommand.ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
at Dapper.SqlMapper.QueryAsync[T](IDbConnection cnn, Type effectiveType, CommandDefinition command) in /_/Dapper/SqlMapper.Async.cs:line 419
能否在Dapper中发送可为空的数组参数到PostgreSQL中 或者我需要找到一个变通方法?
@PeterCsala是正确的。问题是PostgreSQL在服务器端准备查询,所以在C#世界中铸造参数并没有帮助。铸造必须在SQL世界中完成。
工作代码就变成了。
await using var connection = new NpgsqlConnection(_configuration.ConnectionString);
return await connection.QueryAsync<Diamond>(
@"SELECT
id,
name
FROM
product
WHERE
@Names::text[] IS NULL OR name = ANY(@Names);",
new
{
Names = Names,
});