c# - 使用 Dapper 获取 nvarchar(max) 返回一个被修剪为 4000 个字符的字符串。这种行为可以改变吗?

标签 c# json sql-server dapper

我有一个 SQL Server 数据表,其中一列存储了一个 JSON 字符串。 JSON 字符串是序列化的 .net 对象,数据通常超过 4000 个字符。

我有一个用于检索数据的简单存储过程:

    @StageID int,
    @Description varchar(250) = null OUTPUT,
    @Program nvarchar(max) = null OUTPUT
AS
BEGIN
    SET NOCOUNT ON;

    SELECT @Program = StageProgram, @Description = Description 
    FROM StageProgram 
    WHERE StageID = @StageID;

    RETURN 0;
END 

我正在为该列使用数据类型 nvarchar(max)。当我将 .net 对象序列化为 JSON 并使用 Dapper 将其写入数据库时​​,我发现完整的字符串已正确存储在数据库中。

但是,当我尝试检索字符串时,我发现它被裁剪为 4000 个字符,并丢弃了其余数据。

相关代码如下:

DynamicParameters p = new DynamicParameters();

p.Add("@StageID", Properties.Settings.Default.StageID, DbType.Int32, ParameterDirection.Input);
p.Add("@Description", "", DbType.String, direction: ParameterDirection.Output);
p.Add("@Program", "", DbType.String, direction: ParameterDirection.Output);
p.Add("@ReturnValue", DbType.Int32, direction: ParameterDirection.ReturnValue);               

try
{
     int stageID = Properties.Settings.Default.StageID;
     connection.Execute(sql, p, commandType: CommandType.StoredProcedure);                 
     json = p.Get<string>("@Program");
     int r = p.Get<int>("@ReturnValue");                    
}

当我运行它时,字符串 json 被裁剪为 4000 个字符。

如果我使用内置的 .net SQL Server 连接来检索它(为简单起见,使用查询而不是存储过程),则会正确返回完整数据:

SqlCommand getProgram = new SqlCommand("SELECT StageProgram FROM StageProgram WHERE StageID = 1;");
getProgram.Connection = connection;
string json = Convert.ToString(getProgram.ExecuteScalar());

有经验的 Dapper 用户是否能够为这种行为提供解释?

可以改吗?

最佳答案

4000 个字符(当前)the default length for a DBString in Dapper :

image of code from the above link

要获取全文,只需要设置size参数即可:

p.Add("@Program", "", DbType.String, direction: ParameterDirection.Output, size:int.MaxValue);

关于c# - 使用 Dapper 获取 nvarchar(max) 返回一个被修剪为 4000 个字符的字符串。这种行为可以改变吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54095648/

相关文章:

c# - 将 UIImage 转换为流

c# - 使用 WebClient 对网站执行 ping 操作

php - Angularjs:显示对象数组

sql-server - 是否可以使用输出参数化存储过程的 ADODB 结果集中的名称返回字段

c# - "Can' t 找到 PInvoke DLL 'dbnetlib.dll'。“智能设备应用程序中出现错误

c# - 多线程时的意外结果

c# - Yield 如何在 ForEach block 中工作?

java - Jersey - 修改资源内的查询参数

javascript - 使用 JS 库生成图表

sql-server - SQL Server 的 printf