using System.Collections.Generic;
using System.Data.Common;
using System.Threading.Tasks;
public class ProfitAndLossDepartment
public short PlDeptNumber { get; set; }
public string PlDeptName { get; set; }
public static async Task<int> AddPlDeptsAsync(IEnumerable<ProfitAndLossDepartment> plDeptsToAdd, IDbConnection dbConnection, IDbTransaction dbTransaction)
Console.WriteLine($"AddPlDeptsAsync: Received {plDeptsToAdd.Count()} objects.");
INSERT INTO pl_depts (pl_deptnum, pl_deptname, store_pro_flag)
VALUES (@PlDeptNumber, @PlDeptName, 0)";
var numAdded = await dbConnection.ExecuteAsync(insertQuery, plDeptsToAdd, dbTransaction, null, null);
Console.WriteLine($"AddPlDeptsAsync: {numAdded} objects were reported as added to the database.");
public static void Main()
var dbConnection = new Mock<DbConnection>();
var dbTransaction = new Mock<DbTransaction>();
dbConnection.As<IDbConnection>()
.Setup(c => c.BeginTransaction())
.Returns(dbTransaction.Object);
ProfitAndLossDepartment[] testResult = new ProfitAndLossDepartment[]
new ProfitAndLossDepartment { PlDeptNumber = 1, PlDeptName = "First" },
new ProfitAndLossDepartment { PlDeptNumber = 2, PlDeptName = "Second" },
ProfitAndLossDepartment[] plDeptsAdded = null;
Console.WriteLine("TEST 1...");
dbConnection.SetupDapperAsync(c => c.ExecuteAsync(It.IsAny<string>(), It.IsAny<object>(), It.IsAny<IDbTransaction>(), It.IsAny<int?>(), It.IsAny<CommandType?>()))
.ReturnsAsync(testResult.Length);
var numRecsAdded = AddPlDeptsAsync(testResult, dbConnection.Object, dbTransaction.Object).GetAwaiter().GetResult();
Console.WriteLine($"A num rec count of {numRecsAdded} was returned from the call to AddPlDeptsAsync() even though ExecuteAsync() was set up to return {testResult.Length}\r\n");
Console.WriteLine("TEST 2...");
dbConnection.SetupDapperAsync(c => c.ExecuteAsync(It.IsAny<string>(), It.IsAny<object>(), It.IsAny<IDbTransaction>(), It.IsAny<int?>(), It.IsAny<CommandType?>()))
.Callback((string sql, object arg, IDbTransaction transaction, int? commandTimeout, CommandType? commandType) => plDeptsAdded = (arg as IEnumerable<ProfitAndLossDepartment>).ToArray());
AddPlDeptsAsync(testResult, dbConnection.Object, dbTransaction.Object).GetAwaiter();
Console.WriteLine($"The delegate injected into ExecuteAsync() returned {plDeptsAdded?.Length ?? 0} objects even though a collection of {testResult.Length} objects was passed to it via AddPlDeptsAsync().\r\n");
Console.WriteLine("TEST 3...");
dbConnection.SetupDapperAsync(c => c.ExecuteAsync(It.IsAny<string>(), It.IsAny<object>(), It.IsAny<IDbTransaction>(), It.IsAny<int?>(), It.IsAny<CommandType?>()))
.Callback((string sql, object arg, IDbTransaction transaction, int? commandTimeout, CommandType? commandType) => plDeptsAdded = (arg as IEnumerable<ProfitAndLossDepartment>).ToArray())
.ReturnsAsync(testResult.Length);