Dapper icon indicating copy to clipboard operation
Dapper copied to clipboard

Mapping of the sbyte C# type is invalid for Npgsql / Postgres

Open SeppPenner opened this issue 3 years ago • 2 comments

If you use a sbyte type in a model, it is mapped to DbType.SByte. Please check https://github.com/DapperLib/Dapper/blob/b272cc664d933b4b65703d26a79272d549576dff/Dapper/SqlMapper.cs#L173 However, Npgsql for Postgres doesn't seem to support DbType.SByte (An error is thrown that indicates the issue), but DbType.Int16 only. I'm not sure if there has been a recent change in the behaviour in Dapper or if it's a bug of Npgsql though.

The quick hack is to set the dynamic parameters in your query to cast to short like this (Just dummy code, Position is the sbyte property):

await using var connection = await this.GetDatabaseConnection().ConfigureAwait(false);

var sqlParams = new DynamicParameters(new
{
    position = (short)node.Position,
    name = node.Name
});

await connection.ExecuteAsync("UPDATE nodes SET ...", sqlParams).ConfigureAwait(false);

Can you give me information if this is a bug in Dapper or in Npgsql, please?

Version information:

  • Dapper: Latest, 2.0.123.
  • Npgsql: Latest, 6.0.2.

SeppPenner avatar Jan 25 '22 11:01 SeppPenner

IMO it is a bug in your code. Dapper expects your SQL and data to be correct and valid for your target server. Not all servers support signed bytes. If postgresql doesn't support signed bytes, then the correct approach is for your code to not do that. It would be dangerous for Dapper to lie/compensate.

mgravell avatar Jan 25 '22 11:01 mgravell

IMO it is a bug in your code. Dapper expects your SQL and data to be correct and valid for your target server. Not all servers support signed bytes. If postgresql doesn't support signed bytes, then the correct approach is for your code to not do that. It would be dangerous for Dapper to lie/compensate.

Okay, but has the Dapper code changed in the sbyte behaviour lately? This worked as expected (Mapping to Int16) with Npgsql 5.11 and Dapper (Some versions before the latest, I don't remember).

It's not a big issue for us, if sbyte is not supported, we can map it to short manually, but a bit disturbing that it has worked before.

SeppPenner avatar Jan 25 '22 12:01 SeppPenner