I attempted to passing value from object params array to each parameter of stored procedure using loop, but I get this error
'Procedure or function Proc_GetPaging_Product has too many arguments specified.'.
The problem is cmd.Parameters already has parameters when using SqlCommandBuilder.DeriveParameters(cmd) so no need to add value but assigning.
public ServiceResult<T> GetPaging<T>(params object[] values)
{
var result = new ServiceResult<T>();
using(_conn)
{
_conn.Open();
using (SqlCommand cmd = _conn.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "[SalesLT].[Proc_GetPaging_Product]";
SqlCommandBuilder.DeriveParameters(cmd);
int lengthParams = cmd.Parameters.Count;
for (int i = 1; i < lengthParams; i++)
{
cmd.Parameters.AddWithValue(cmd.Parameters[i].ParameterName, values[i - 1]);
}
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var item = Activator.CreateInstance<T>();
var properties = typeof(T).GetProperties();
foreach (var property in properties)
{
//Type convertTo = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
property.SetValue(item, reader[property.Name], null);
}
result.ListResult.Add(item);
}
reader.NextResult();
}
}
}
return result;
}
SqlCommandBuilder.DeriveParameters(cmd)adds parameters to command based on the definition of stored proc. Andcmd.Parameters.AddWithValueadds new parameter. So basically you are trying to add the same parameters again to the command.