I've written a very light wrapper around Dapper to help with unit testing and streamlining the Dapper commands I need.
Execute()
is a method created to remove the code duplication of opening and closing the database connection and enlisting it in a transaction. The code is very quick at inserts with this method (200,000 inserts in less than 30 secs).
I'm wondering if I've made any obvious mistakes with regards to Dapper and performance.
For instance, should a single insert or read explicitly enlist a transaction, or would they be faster with an ambient transaction?
public class DappperService
{
private readonly string sqlConnection;
public DappperService(string sqlConnection)
{
this.sqlConnection = sqlConnection;
DapperExtensions.DapperExtensions.DefaultMapper = typeof(PluralizedAutoClassMapper<>);
}
public T Get<T>(int id) where T : class
{
return Execute((x, t) => x.Get<T>(id, t));
}
public bool Delete<T>(T dto) where T : class
{
return Execute((x, t) => x.Delete(dto,t));
}
public dynamic Insert<T>(T dto) where T : class
{
return Execute((x, t) => x.Insert(dto,t));
}
public void Insert<T>(List<T> dtoList) where T : class
{
IEnumerable<T> enu = dtoList;
using (var con = new SqlConnection(sqlConnection))
{
con.Open();
var trans = con.BeginTransaction();
con.Insert(enu, trans);
trans.Commit();
con.Close();
}
}
public IEnumerable<T> GetList<T>() where T : class
{
return Execute((x, t) => x.GetList<T>(transaction:t));
}
public dynamic Execute(Func<SqlConnection, SqlTransaction, dynamic> action)
{
using (var con = new SqlConnection(sqlConnection))
{
con.Open();
var trans = con.BeginTransaction();
var result = action(con, trans);
trans.Commit();
con.Close();
return result;
}
}
}