简体   繁体   English

将 SQL 参数集合传递给函数

[英]Passing a SQL parameter collection to a function

When writing ASP.NET CRUD applications in C#, I often find myself inserting a lot of repetitive boilerplate codes for fetching SQL Server queries into data tables, fetching scalar values from queries into variables, calling stored procedures, and so forth.在用 C# 编写 ASP.NET CRUD 应用程序时,我经常发现自己插入了大量重复的样板代码,用于将 SQL Server 查询提取到数据表中、从查询中提取标量值到变量中、调用存储过程等等。

Recently, I've been trying to refactor this by creating generic classes and methods to handle these basic tasks.最近,我一直在尝试通过创建通用类和方法来处理这些基本任务来重构它。 However, in order for these to work properly, they need to be able to take an arbitrary number of parameters.但是,为了使它们正常工作,它们需要能够采用任意数量的参数。 The built-in SqlParameterCollection class seemed the obvious first choice, but unfortunately this class cannot be instantiated from user code.内置的SqlParameterCollection类似乎是显而易见的首选,但不幸的是,该类无法从用户代码中实例化。 The next option was to pass a List<SqlParameter> to the function, and then use foreach to add its contents to the built-in parameter collection of the SqlCommand .下一个选项是将List<SqlParameter>传递给函数,然后使用foreach将其内容添加到SqlCommand的内置参数集合中。 This worked, but the declaration is a bit clumsy.这行得通,但声明有点笨拙。

To create the list in code before calling the function, I have to do something like this:要在调用函数之前在代码中创建列表,我必须执行以下操作:

List<SqlParameter> ParameterList = new List<SqlParameter>
{
    new SqlParameter() { ParameterName = "@Parameter1", SqlDbType = SqlDbType.VarChar, Value = InputVariable1 },
    new SqlParameter() { ParameterName = "@Parameter2", SqlDbType = SqlDbType.VarChar, Value = InputVariable2 },
    new SqlParameter() { ParameterName = "@Parameter3", SqlDbType = SqlDbType.VarChar, Value = InputVariable3 }
};

This is hard to read on smaller monitors and still contains a lot of repetitious boilerplate.这很难在较小的显示器上阅读,并且仍然包含许多重复的样板文件。 So my next step was to create a custom class with an overloaded Add method so that this would not be needed.所以我的下一步是使用重载的 Add 方法创建一个自定义类,这样就不需要了。 I've read that it is bad to subclass List in C#, so I used Collection instead:我读过在 C# 中子类化List是不好的,所以我使用Collection代替:

public class ParameterCollection : Collection<SqlParameter>
{
    public void Add(string    ParameterName,
                    SqlDbType ParameterType,
                    object    ParameterValue)
    {
        // Create the parameter and add it to the list
        SqlParameter Parameter = new SqlParameter();
        Parameter.ParameterName = ParameterName;
        Parameter.SqlDbType     = ParameterType;
        Parameter.Value         = ParameterValue;
        base.Add(Parameter);

        // Done
        return;
    }
}

I can then declare a parameter collection like this:然后我可以像这样声明一个参数集合:

ParameterCollection Parameters = new ParameterCollection
{
    // name          type               value
    { "@Parameter1", SqlDbType.VarChar, InputVariable1 },
    { "@Parameter2", SqlDbType.VarChar, InputVariable2 },
    { "@Parameter3", SqlDbType.VarChar, InputVariable3 }
};

My question is this: Is there any quicker/easier way to perform this task that I'm overlooking?我的问题是:有没有更快/更简单的方法来执行我忽略的这项任务? And are there any potential hidden pitfalls or bad practices in the way I'm currently doing it?我目前的做法是否有任何潜在的隐藏陷阱或不良做法?

您可能忽略的一件事是Add返回Add的参数,这允许我们在同一语句中设置值:

cmd.Parameters.Add("@Parameter1", SqlDbType.VarChar).Value = paramValue;

Rather than instantiating and passing a collection—which, as you say, is hampered by SqlParameterCollection having no public constructor—you may pass the collection indirectly, by passing the SqlCommand itself. 而不是实例化和传递集合 - 正如你所说,它受到没有公共构造函数的SqlParameterCollection阻碍 - 你可以通过传递SqlCommand本身来间接传递集合。 Your generic classes and methods may then add parameters to SqlCommand.Parameters , removing the need for you to instantiate a separate collection. 然后,您的泛型类和方法可以向SqlCommand.Parameters添加参数,从而无需实例化单独的集合。

There are several ways to perform this action.有几种方法可以执行此操作。

First: You must declare the new parameter.首先:您必须声明新参数。

cmd.Parameters.Add("@Parameter1", SqlDbType.VarChar, 50 //the size of Varchar);

Then you add the value.然后添加值。

cmd.Parameters["@Parameter1"].Value = paramValue;

I prefer to use Dapper extension for such things.我更喜欢使用 Dapper 扩展来处理这些事情。 It is way easier, the syntax is more readable and overall just love it.它更容易,语法更具可读性,总的来说就是喜欢它。 Check the link, you might like what you see: https://dapper-tutorial.net/检查链接,您可能会喜欢您所看到的: https ://dapper-tutorial.net/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM