使用Dapper和Postgresql - citext数据类型

时间:2016-08-30 23:21:34

标签: postgresql dapper npgsql

我不确定是否有办法支持这一点,但是我无法让Dapper将字符串参数值映射到Postgresql citext数据类型,因为它似乎使用了文本类型。

特别是,我正在尝试调用一个接受citext参数的函数 - 我得到的错误是:

var c = ConnectionManager<T>.Open();
string sql = @"select * from ""dbo"".""MyFunction""(@schemaName, @tableName);";
var param = new
{
    schemaName = schema,
    tableName = table
};

string insecureSalt = c.QueryMultiple(sql, param).Read<string>().FirstOrDefault();
ConnectionManager<T>.Close(c);

Error: Npgsql.PostgresException: 42883: function dbo.MyFunction(text, text) does not exist.

匹配的签名是函数dbo.MyFunction(citext,citext),所以很明显它无法使用默认映射找到它。

根据Npgsql - http://www.npgsql.org/doc/types.html我需要能够指定NpgsqlDbType.Citext作为类型,但我找不到使用Dapper的方法。

解决感谢Shay的回答,完整的解决方案:

var c = ConnectionManager<T>.Open();
string sql = @"select * from ""dbo"".""MyFunction""(@schemaName, @tableName);";
var param = new
{
    schemaName = new CitextParameter(schema),
    tableName = new CitextParameter(table)
};

string insecureSalt = c.QueryMultiple(sql, param).Read<string>().FirstOrDefault();
ConnectionManager<T>.Close(c);

public class CitextParameter : SqlMapper.ICustomQueryParameter
{
    readonly string _value;

    public CitextParameter(string value)
    {
        _value = value;
    }

    public void AddParameter(IDbCommand command, string name)
    {
        command.Parameters.Add(new NpgsqlParameter
        {
            ParameterName = name,
            NpgsqlDbType = NpgsqlDbType.Citext,
            Value = _value
        });
    }
}

2 个答案:

答案 0 :(得分:4)

您可能需要创建一个CitextParameter来扩展ICustomQueryParameter。此API允许您将任意DbParameter实例传递给Dapper - 在这种情况下,它将是NpgsqlParameter的一个实例,其NpgsqlDbType设置为Citext。

这样的事情应该有效:

class CitextParameter : SqlMapper.ICustomQueryParameter
{
    readonly string _value;

    public CitextParameter(string value)
    {
        _value = value;
    }

    public void AddParameter(IDbCommand command, string name)
    {
        command.Parameters.Add(new NpgsqlParameter
        {
            ParameterName = name,
            NpgsqlDbType = NpgsqlDbType.Citext,
            Value = _value
        });
    }
}

答案 1 :(得分:0)

When you write the SQL query, you can cast the parameter value like cast(@param as citext).

in my case below worked correctly. (usr is a class object)

string sql = "select * from users where user_name = cast(@user_name as citext) and password = @password;";
IEnumerable<users> u = cnn.Query<users>(sql, usr);

In your case, you can change the query like below and see if that works

string sql = @"select * from ""dbo"".""MyFunction""(cast(@schemaName as citext), cast(@tableName as citext));";