Dapper - Parameter Dynamic

Description

Create and use a parameter in a Dapper method.

Single

Execute a single time a SQL Command.

  1. var sql = "EXEC Invoice_Insert";
  2. using (var connection = My.ConnectionFactory())
  3. {
  4. connection.Open();
  5. DynamicParameters parameter = new DynamicParameters();
  6. parameter.Add("@Kind", InvoiceKind.WebInvoice, DbType.Int32, ParameterDirection.Input);
  7. parameter.Add("@Code", "Many_Insert_0", DbType.String, ParameterDirection.Input);
  8. parameter.Add("@RowCount", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);
  9. connection.Execute(sql,
  10. parameter,
  11. commandType: CommandType.StoredProcedure);
  12. int rowCount = parameter.Get<int>("@RowCount");
  13. }

Many

Execute many times a SQL Command

  1. var sql = "EXEC Invoice_Insert";
  2. var parameters = new List<DynamicParameters>();
  3. for (var i = 0; i < 3; i++)
  4. {
  5. var p = new DynamicParameters();
  6. p.Add("@Kind", InvoiceKind.WebInvoice, DbType.Int32, ParameterDirection.Input);
  7. p.Add("@Code", "Many_Insert_" + (i + 1), DbType.String, ParameterDirection.Input);
  8. p.Add("@RowCount", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);
  9. parameters.Add(p);
  10. }
  11. using (var connection = My.ConnectionFactory())
  12. {
  13. connection.Open();
  14. connection.Execute(sql,
  15. parameters,
  16. commandType: CommandType.StoredProcedure
  17. );
  18. var rowCount = parameters.Sum(x => x.Get<int>("@RowCount"));
  19. }