如何在Sybase ASE中使用Dapper的强类型查询参数?

时间:2011-10-19 15:20:57

标签: .net ado.net sybase-ase dapper

Dapper可以将查询参数作为匿名对象传递,并支持任何ADO.NET数据提供程序。但是,对Sybase 15 ADO.NET驱动程序运行以下查询时:

using (var connection = new AseConnection("..."))
{
    connection.Open();

    var results = connection.Query<Foo>(
        "dbo.sp_columns", new { table_name = "dbo.sysusers"}, 
        commandType: CommandType.StoredProcedure);
}

...抛出以下错误:

Sybase.Data.AseClient.AseException: Procedure sp_columns expects parameter @table_name, which was not supplied.

at Sybase.Data.AseClient.AseCommand.ᜁ(Int32 A_0)
at Sybase.Data.AseClient.AseCommand.ᜄ()
at Sybase.Data.AseClient.AseCommand.ᜀ(CommandBehavior A_0)
at Sybase.Data.AseClient.AseCommand.System.Data.IDbCommand.ExecuteReader()
at Dapper.SqlMapper.<QueryInternal>d__13`1.MoveNext() in SqlMapper.cs: line 579
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList(IEnumerable`1 source)
at Dapper.SqlMapper.Query(IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Boolean buffered, Nullable`1 commandTimeout, Nullable`1 commandType) in SqlMapper.cs: line 536

将其更改为使用“@table_name”设置的Dapper DynamicParameters也不起作用。

如何使用Dapper将强类型参数传递给Sybase?

1 个答案:

答案 0 :(得分:8)

据我所知,原因似乎与Sybase的AseParameter类有关,而且没有正确地将DbType映射到AseDbType值。

您可以通过定义自定义Dapper IDynamicParameters集并直接用AseParameter个对象填充它来解决此问题:

public class AseCommandParameters : List<AseParameter>, SqlMapper.IDynamicParameters
{
    public void AddParameters(IDbCommand command, SqlMapper.Identity identity)
    {
        foreach (var parameter in this)
            command.Parameters.Add(parameter);
    }
}

然后将实例传递给查询:

using (var connection = new AseConnection("..."))
{
    connection.Open();

    var parameters = new AseCommandParameters
    {
        new AseParameter("@table_name", "dbo.sysusers")
    };

    var results = connection.Query<Foo>("dbo.sp_columns", parameters, 
        commandType: CommandType.StoredProcedure);
}

这样做,并且还允许您为每个参数指定AseDbType