存储过程返回varbinary(max)作为输出。我不明白如何使用Dapper访问这些信息。
下面是一些简化的示例代码,说明了这个问题。我向StoredProcedure提供了一些参数,我希望得到一个照片,它在SQL Server上存储为varbinary(max)。
对于varbinary没有DbType。我尝试使用DbType.Binary,但这在Dapper中导致了异常。如果我去掉了photo参数,我希望返回的所有其他参数(为了简洁起见,这些参数都是从样本中删除的)都是有效的。因此,唯一的问题是检索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 {}
}更新:
我发现我必须在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 {}这将导致检索包含预期图像数据的字节数组。
发布于 2019-02-07 00:13:10
您可以尝试:
p.Add("@Photo", dbType: DbType.Binary, direction: ParameterDirection.Output, size: -1);它似乎在本地对我有效,这就是varchar(max)和nvarchar(max)的映射方式(除了分别作为DbType.AnsiString和DbType.String ),所以它是一致的。
https://stackoverflow.com/questions/54557416
复制相似问题