本文介绍了dapper中字符串到varchar的处理程序映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Dapper中找到以下代码:

I found the following code in Dapper:

sealed partial class DbString : Dapper.SqlMapper.ICustomQueryParameter
{
    ...

    public void AddParameter(IDbCommand command, string name)
    {
        ...
        var param = command.CreateParameter();
        param.ParameterName = name;
        param.Value = (object)Value ?? DBNull.Value;
        if (Length == -1 && Value != null && Value.Length <= 4000)
        {
            param.Size = 4000;
        }
        else
        {
            param.Size = Length;
        }
        ...
    }
}

为什么比较长度为4000?

Why does it compare the length to 4000?

推荐答案

查询计划缓存。

以下查询是独立的:

select @foo

select @foo

如果您感到困惑,那是因为我没有显示的位是参数声明-在第一个是 nvarchar(12),第二个是 nvarchar(20)。代码试图避免的是一个查询,执行两次-例如,使用 hello (5个字符)执行一次,使用 world!(6个字符),具有两个单独的查询计划;这比允许双方共享计划的效率要低得多,而且这种选择对事物产生负面影响的机会很少。

If you are confused, that is because the bit I didn't show was the parameter declaration - in the first one it is nvarchar(12) and in the second one it is nvarchar(20). What the code is trying to avoid is a single query, executed twice - for example once with hello (5 characters) and once with world! (6 characters) having two separate query-plans; that is much less efficient than allowing both to share a plan, and the number of occasions where this choice would negatively impact things is vanishingly small.

通过将长度标准化为任意值,它允许大多数常用值使用相同的查询计划缓存。 4000 是相当任意的(好吧,它之所以被选择是因为 nvarchar(4000)是开始之前的最大大小进入 max 区域),也可能是 200 或任何您想要的内容。该代码在大多数时间 值都较短的基础上工作,因此,如果存在 个较大的值,它们将是例外而不是规则。

By standardising the length at some arbitrary value, it allows most common values to use the same query-plan cache. The 4000 is fairly arbitrary (well, actually it was chosen because nvarchar(4000) is the maximum size before it starts getting into max territory), and it could just as well have been 200, or whatever you want. The code is working on the basis that most of the time values are fairly short, so if there are larger values, they will be the exception rather than the rule.

请注意,只有在未明确设置 Length 的情况下,所有这些操作才会发生;如果您想对此进行更多控制,只需将设置 .Length 设置为您想要的内容。关键属性为:

Note that all of this only happens if you haven't set the Length explicitly; if you want more control over this, simply set .Length to what you want. The key properties are:


  • IsAnsi -在unicode / not之间切换- n [n] [var] char(len)

  • IsFixedLength -在固定/可变长度之间切换-在 [n] [var] char中的 var len)

  • 长度- len [n] [var] char(len)

  • Value -实际内容

  • IsAnsi - switches between unicode/not - the n in [n][var]char(len)
  • IsFixedLength - switches between fixed/variable length - the var in [n][var]char(len)
  • Length - the len in [n][var]char(len)
  • Value - the actual contents

这篇关于dapper中字符串到varchar的处理程序映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 17:14