7

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?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Kjartan
  • 18,591
  • 15
  • 71
  • 96
  • 1
    Does this answer your question? [How do I pass a table-valued parameter to Dapper in .NET Core?](https://stackoverflow.com/questions/41132350/how-do-i-pass-a-table-valued-parameter-to-dapper-in-net-core) – TylerH Apr 14 '22 at 15:03

2 Answers2

4

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);
  }
William Xifaras
  • 5,212
  • 2
  • 19
  • 21
0

You should be able to pass in an IEnumerable<SqlDataRecord>, like this. It's in System.Data, and it's not deprecated.

Community
  • 1
  • 1
bbsimonbb
  • 27,056
  • 15
  • 80
  • 110