You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过存储过程将byte[]类型数据传入SQL的VarBinary(Max)?

解决byte[]传入SQL Server存储过程显示System.byte[]的问题

问题原因

直接通过字符串插值传递byte[]参数时,.NET会调用byte[]默认的ToString()方法,返回的是字符串"System.byte[]",而非实际的二进制数据,导致SQL Server无法将其解析为VARBINARY(MAX)类型。

解决方案:使用参数化查询

不要直接拼接SQL字符串,改用SqlParameter传递参数,既能正确传递二进制数据,还能避免SQL注入风险。

修改后的C#代码

替换原代码中ExecuteSqlRawAsync的调用部分:

// 创建参数数组
var parameters = new[]
{
    new SqlParameter("@Mobile", Mobile),
    new SqlParameter("@FirstName", FirstName),
    new SqlParameter("@LastName", LastName),
    new SqlParameter("@Email", Email),
    new SqlParameter("@Age", Age),
    new SqlParameter("@PasswordHash", SqlDbType.VarBinary) { Value = passwordHash },
    new SqlParameter("@PasswordSalt", SqlDbType.VarBinary) { Value = passwordSalt }
};

// 调用存储过程并传入参数
var dbUsers = await _context.Database.ExecuteSqlRawAsync(
    "RegisterNewUser @Mobile, @FirstName, @LastName, @Email, @Age, @PasswordHash, @PasswordSalt", 
    parameters);

修正存储过程语法(建议)

你的存储过程缺少AS关键字和BEGIN/END块,可能引发语法错误,修正后如下:

ALTER PROCEDURE [dbo].[RegisterNewUser]
    @Mobile NVarChar(100),
    @FirstName NVarChar(250),
    @LastName NVarChar(250),
    @Email NVarChar(250),
    @Age int,
    @PasswordHash VarBinary(max),
    @PasswordSalt VarBinary(max)
AS
BEGIN
    SET NOCOUNT ON 

    INSERT INTO Users (Mobile, FirstName, LastName, Email, Age,
                       PasswordHash, PasswordSalt)
    VALUES (@Mobile, @FirstName, @LastName, @Email, @Age,
            @PasswordHash, @PasswordSalt)
END

说明

参数化查询会自动处理byte[]到VARBINARY(MAX)的类型映射,确保二进制数据准确传递到SQL Server,完全满足你不使用字符串格式传递参数的要求。

内容的提问来源于stack exchange,提问作者Mahdi Attar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 04:40:29