While trying to pass a table in as a parameter to a stored procedure via Dapper, I came across this SO answer, which indicates that it is directly supported in Dapper.
In .NET core however, DataTable seems not to be implemented, so this does not work.
Is there another easy way of passing a custom / user-defined table in as a parameter to a stored procedure using Dapper?
For now, you will have to create a class that implements SqlMapper.IDynamicParameters for each table value type.
Modified example (not tested)
http://todothinkofname.net/2016/05/30/Dapper-with-Net-core/
public class ParameterTvp : SqlMapper.IDynamicParameters
{
private readonly IEnumerable<string> _parameters;
public ParameterTvp(IEnumerable<string> parameters)
{
_parameters = parameters;
}
public void AddParameters(IDbCommand command, SqlMapper.Identity identity)
{
var sqlCommand = (SqlCommand) command;
sqlCommand.CommandType = CommandType.StoredProcedure;
var items = new List<SqlDataRecord>();
foreach (var param in _parameters)
{
var rec = new SqlDataRecord(new SqlMetaData("Parameter", SqlDbType.NVarChar, 100));
rec.SetString(0, param);
items.Add(rec);
}
var p = sqlCommand.Parameters.Add("@param", SqlDbType.Structured);
p.Direction = ParameterDirection.Input;
p.TypeName = "ParameterTableType";
p.Value = items;
}
}
Usage
using (var connection = new SqlConnection(connectionString))
{
var parameters = new ParameterTvp(new List<string>() { "XXXXXXXX" });
connection.Execute("test", parameters);
}
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