[英]C# ASP.NET: create general method to call Stored Procedure with any number of parameters
In the project I'm working to in this period I have to work a lot with stored procedures in SQL Server, actually I use this method (using Dapper): 在这个时期我要处理的项目中,我必须在SQL Server中处理很多存储过程,实际上我使用了这种方法(使用Dapper):
public static foo_type call_stored_procedure(string stored_procedure_name, string ConnectionString, type_param_1 param1, type_param_2 param2)
{
using (var connection = new SqlConnection(ConnectionString))
{
connection.Open();
var server_return = connection.Query<foo_type>(stored_procedure_name,
new { param1 = param1, param2 = param2 }, commandType: CommandType.StoredProcedure);
if (server_return != null)
return server_return;
}
return null;
}
This method has the following two problems: 此方法存在以下两个问题:
foo_type
type foo_type
类型的对象 I'd like to make this method general, so 我想将此方法通用化,所以
The function declaration will be something like: 函数声明将类似于:
public static <T> call_stored_procedure(string stored_procedure_name, string ConnectionString, <T> type, <T> params...)
Is there a way to do something like this in C#? 有没有办法在C#中做这样的事情?
Try this: 尝试这个:
public T CallStoredProcedure<T>(connectionString, procName, params object[] parameters)
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
var server_return = connection.Query<T> (procName, parameters, commandType: CommandType.StoredProcedure);
if (server_return != default(T))
return server_return;
}
return default(T);
}
Try passing a Dictionary<string,object>
as a parameter and return object
. 尝试将
Dictionary<string,object>
作为参数传递并返回object
。
It is similar to how ASP.NET MVC allows any number of parameters to be sent to an Action. 这类似于ASP.NET MVC允许将任意数量的参数发送到操作的方式。 Your stored procedure will retrieve the parameters it needs from the dictionary by their key.
您的存储过程将通过其键从字典中检索所需的参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.