对于 varbinary 数据类型,DynamicParameters (Dapper) 的正确用法是什么?

Q''*_*Q'' 5 dapper dynamicparameters

除其他外,存储过程返回 varbinary(max) 作为输出。我不明白如何使用 Dapper 访问此信息。

下面是一些说明问题的简化示例代码。我向 StoredProcedure 提供一些参数,并希望返回一张在 SQL Server 上存储为 varbinary(max) 的照片。

varbinary 没有 DbType。我尝试使用 DbType.Binary 但这会导致 Dapper 中出现异常。如果我去掉照片参数,我期望返回的所有其他参数(为了简洁起见,从示例中删除了这些参数)都将起作用。所以唯一的问题是检索 varbinary 数据。

实现这一目标的正确方法是什么?

using (var connection = new System.Data.SqlClient.SqlConnection(HelperClassesBJH.HelperMethods.ConString("ProductionLocal")))
        {
            connection.Open();

            DynamicParameters p = new DynamicParameters();

            p.Add("@OpID", id, DbType.Int32, ParameterDirection.Input);
            p.Add("@StageID", Properties.Settings.Default.StageID, DbType.Int32, ParameterDirection.Input);               
            p.Add("@Photo", dbType: DbType.Binary, direction: ParameterDirection.Output);                

            try
            {
                connection.Execute(sql, p, commandType: CommandType.StoredProcedure);

                op.Photo = p.Get<byte[]>("@Photo");                    
            }
            catch {}

        }
Run Code Online (Sandbox Code Playgroud)

更新:

我发现我必须在 DynamicParameters 构造函数中提供“value”参数。这避免了我遇到的异常。我无法理解为什么我需要提供一个值,因为该参数是一个输出,并且我提供的值没有被使用。这是修改后的代码:

DynamicParameters p = new DynamicParameters();
MemoryStream b = new MemoryStream();

p.Add("@OpID", id, DbType.Int32, ParameterDirection.Input);
p.Add("@StageID", Properties.Settings.Default.StageID, DbType.Int32, ParameterDirection.Input);                
p.Add("@Photo", b, DbType.Binary, direction: ParameterDirection.Output);                

try
  {
     connection.Execute(sql, p, commandType: CommandType.StoredProcedure);

     op.Photo = p.Get<byte[]>("@Photo");
  }
 catch {}
Run Code Online (Sandbox Code Playgroud)

这会导致检索包含预期图像数据的字节数组。

Mar*_*ell 3

你可以尝试:

p.Add("@Photo", dbType: DbType.Binary, direction: ParameterDirection.Output, size: -1);
Run Code Online (Sandbox Code Playgroud)

它似乎在本地对我有用,这就是varchar(max)和 的nvarchar(max)映射方式(分别除了 asDbType.AnsiStringDbType.String),因此它是一致的。