I am currently developing an application using C# (Visual Studio 2019)and SQL Server 2017 using Dapper. Below is a routine that works fine right now to execute a stored procedure in SQL Server.
The C# code uses the MVVM framework, and I currently have 60 model classes to map the tables in the SQL Server database. There are about 120 stored procedures that produce results that are mapped to the model classes using Dapper.
Consider the following code snippet as pseudocode (but it actually works to execute the stored procedure and return the correct results).
public List<SomeDefinedModel> ExecuteSQLSPROC(string SPROCName, SqlParameter[] parameters)
{
using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(DBHelper.CNNVal("MYLocalServer")))
{
System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand();
command.Connection = (SqlConnection)connection;
command.CommandText = SPROCName;
DynamicParameters parms = new DynamicParameters();
for (int i = 0; i < parameters.Length; i++)
{
var parmname = parameters[i].ParameterName;
var parmvalue = parameters[i].Value;
parms.Add(parmname, parmvalue);
}
var output = connection.Query<SomeDefinedModel>(SPROCName, parms, commandType: CommandType.StoredProcedure).ToList();
return output;
}
}
I want to change this routine so the routine so that it method signature is as follows:
public List<TheNameOfTheModelToMap> ExecuteSQLSPROC(string SPROCName, SqlParameter[] parameters, TheNameOfTheModelToMap)
That is, the designation of the model to which Dapper is to map is a variable - it can be any valid model. I have define the variable TheNameOfTheModelToMap as type object, and the return value as var, as List<object>, and so forth. They produce errors because of this syntax:
var output = connection.Query<TheNameOfTheModelToMap>(SPROCName, parms, commandType: CommandType.StoredProcedure).ToList();
I want to comply with the principles of DRY and code just one method to accept ANY model designation, ANY stored procedure designation and have Dapper map the query results. Any possibilities?
public List<T> ExecuteSQLSPROC<T>(string SPROCName, SqlParameter[] parameters)?SqlCommandhere, you don't seem to use it, and surely Dapper sorts that out for you anywaypublic List<TheNameOfTheModelToMap> ExecuteSQLSPROC(string SPROCName, SqlParameter[] parameters, object TheNameOfTheModelToMap)? It's not clear from your signature what the type of theTheNameOfTheModelToMapparameter is.