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):
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 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#?
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
.
It is similar to how ASP.NET MVC allows any number of parameters to be sent to an Action. Your stored procedure will retrieve the parameters it needs from the dictionary by their key.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.