I am attempting to call a stored procedure that accepts a table valued parameter.
I am following guidelines on this question, implementing a custom parameter type:
internal class IntDynamicParam
{
string name;
IEnumerable<int> numbers;
public IntDynamicParam(string name,IEnumerable<int> numbers)
{
this.name = name;
this.numbers = numbers;
}
public void AddParameters(IDbCommand command)
{
var sqlCommand = (SqlCommand)command;
sqlCommand.CommandType = CommandType.StoredProcedure;
List<Microsoft.SqlServer.Server.SqlDataRecord> number_list = new List<Microsoft.SqlServer.Server.SqlDataRecord>();
// Create an SqlMetaData object that describes our table type.
Microsoft.SqlServer.Server.SqlMetaData[] tvp_definition = { new Microsoft.SqlServer.Server.SqlMetaData("n", SqlDbType.Int) };
foreach (int n in numbers)
{
// Create a new record, using the metadata array above.
Microsoft.SqlServer.Server.SqlDataRecord rec = new Microsoft.SqlServer.Server.SqlDataRecord(tvp_definition);
rec.SetInt32(0, n); // Set the value.
number_list.Add(rec); // Add it to the list.
}
// Add the table parameter.
var p = sqlCommand.Parameters.Add("@" +name, SqlDbType.Structured);
p.Direction = ParameterDirection.Input;
p.TypeName = "int_list_type";
p.Value = number_list;
}
}
and am attempting to use this as follows:
var p = new DynamicParameters();
p.AddDynamicParams(new IntDynamicParam("@IDList", new int[] { 1000, 2000, 3000 }));
p.Add("@StartRow", startRow);
p.Add("@EndRow", endRow);
p.Add("@OrderByField", orderByField.ToString());
p.Add("@OrderBy", orderBy.ToString());
p.Add("@TotalRows", 0, dbType: DbType.Int32, direction: ParameterDirection.Output);
var v = cnn.Query<venue>(spName, p,
commandType: CommandType.StoredProcedure).ToList<IDBVenueLite>();
However the parameter '@IDList' is not passed. Clearly AddDynamicParams is not the way to go, can anyone help me out?
Historically table-valued-parameters haven't been a huge focus in dapper; mainly because they only work on SqlConnection
(dapper tries to target arbitrary providers, including "decorated" ADO.NET providers - i.e. where a SqlConnection
is hiding underneath some wrapper). What you could do is implement IDynamicParameters
manually (or just borrow the existing DynamicParameters
class) to add this functionality:
void SqlMapper.IDynamicParameters.AddParameters(System.Data.IDbCommand command,
SqlMapper.Identity identity)
{
...
// and then whatever the code is...
((SqlCommand)command).Parameters
.AddWithValue(...,...).SqlDbType = System.Data.SqlDbType.Structured;
...
}
I will also endeavor to make the concrete DynamicParameters
class more polymorphic here, so that in a future build you can just override
a single method, detect a TVP-ish type, and add the parameter manually.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With