c# - 缓存中的 Ado.net 和 Sp 参数?

标签 c# .net ado.net sqlparameter

我正在阅读 Microsoft.ApplicationBlocks.Data 的代码( code is here )

但是我注意到一些奇怪的事情:

在其中一个函数 (executeNonQuery) 中,他尝试从缓存中读取 Sp 的参数,如果不存在,他将它们放入缓存中(不是 asp.net 缓存 - 而是一个内部 HashSet)

public static int ExecuteNonQuery(string connectionString, string spName, params SqlParameter[] parameterValues)
    {
        if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");
        if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName");
        // If we receive parameter values, we need to figure out where they go
        if ((parameterValues != null) && (parameterValues.Length > 0))
        {
            // Pull the parameters for this stored procedure from the parameter cache (or discover them & populate the cache)
            //------------------------------------

            SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName);

           //------------------------------------
            // Assign the provided values to these parameters based on parameter order
            AssignParameterValues(commandParameters, parameterValues);
            // Call the overload that takes an array of SqlParameters
            return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName, commandParameters);
        }
        else
        {
            // Otherwise we can just call the SP without params
            return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName);
        }
    }

请看隔离线。

他们为什么要这么做?如果我在 Cache 中有参数,它对我有什么帮助?我要从我的 dal 发送参数 无论如何 ...(而且我必须将我的参数发送到 SP)...

我错过了什么?

最佳答案

如果没有缓存,他们最终会在每次调用 ExecuteNonQuery 时调用 SqlCommandBuilder.DeriveParameters,为此 MSDN状态:

DeriveParameters requires an additional call to the database to obtain the information. If the parameter information is known in advance, it is more efficient to populate the parameters collection by setting the information explicitly.

因此缓存检索到的参数信息以避免这些额外的调用是有意义的。

更新:

Im gonna send the params anyway from my dal ...( and I must send my params to a SP)...

请注意 int ExecuteNonQuery(string connectionString, string spName, params object[] parameterValues) 重载——您可以发送也可以不可以发送参数。

关于c# - 缓存中的 Ado.net 和 Sp 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13073255/

相关文章:

c# - 如何在我的 Web Api 方法中处理 HttpResponseMessage?

c# - 在 WPF 中填充 ListView 项目

c# - 反汇编具有动态类型的 .NET c# 库

c# - 映射到嵌套类

c# - 从表中删除行而不先检查它们是否存在

c# - 使用 c# 或 c++ 的分水岭

c# - 如何解析 yaml 字符串

c# - 表值参数的排序顺序是否保证保持不变?

sql - 混合使用 ADO.NET 和 LINQ-TO-SQL 不好吗?我的数据层不工作

vb.net - 处理日期时间和空值