Skip to content

Parameter size overwritten after custom TypeHandler #2141

Closed

Description

@mroth-omega

When providing a custom TypeHandler for the type string, the IDbDataParameter.Size property is overwritten after calling the custom TypeHandler.SetValue method. The database provider I'm using does not accept nvarchar parameters with such a large size. The size property is being overridden by the block of code starting here:

if (prop.PropertyType == typeof(string))

I am unable to create a pull request, but my suggested fix is to move that conditional block prior to calling the custom handler just above. Or, if necessary to set the size after setting the value, add a check for a valid size before overriding it with the DbString.DefaultSize constant loaded earlier in the function.

Here is an example type handler and setup code to reproduce the issue:

// Custom string type handler
private class StringTypeHandler : SqlMapper.TypeHandler<string>
{
    public override void SetValue(IDbDataParameter parameter, string? value)
    {
        int size = Math.Max(1, value?.Length ?? 100);
        parameter.DbType = DbType.String;
        parameter.Value = value;
        parameter.Size = size;
    }

    public override string? Parse(object value)
    {
        return value as string;
    }
}

// Replacing the default string type handler
SqlMapper.RemoveTypeMap(typeof(string));
SqlMapper.AddTypeHandler(new StringTypeHandler());

IDbConnection conn;
conn.Execute(cmd, new { p = "hello" })

I ran into this issue using Dapper version 2.1.35. My project is .NET 8 targeting win-x86 with an OdbcConnection using driver Microsoft Access Driver (*.mdb). Trying to execute a statement resulted in this error: System.Data.Odbc.OdbcException (0x80131937): ERROR [HY104] [Microsoft][ODBC Microsoft Access Driver]Invalid precision value. I can workaround this error by changing the type passed for parameters to use DbString. However, I would like to reuse a datatype that has string properties so I created a custom TypeHandler<string>. Through debugging, I found that the parameter size was set to 4000 when executing the command, despite my handler setting the size just moment earlier.

Activity

  1. changed the title [-]Parameter size overwritten after customer TypeHandler[/-] [+]Parameter size overwritten after custom TypeHandler[/+] on Jan 7, 2025
  2. added a commit that references this issue on Nov 20, 2026
    98104ac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions