How to implement Unit Of Work pattern with Dapper?

This Git project is very helpful. I started from the same and did some changes as per my need. public sealed class DalSession : IDisposable { public DalSession() { _connection = new OleDbConnection(DalCommon.ConnectionString); _connection.Open(); _unitOfWork = new UnitOfWork(_connection); } IDbConnection _connection = null; UnitOfWork _unitOfWork = null; public UnitOfWork UnitOfWork { get { return _unitOfWork; … Read more

Correct use of multimapping in Dapper

I just ran a test that works fine: var sql = “select cast(1 as decimal) ProductId, ‘a’ ProductName, ‘x’ AccountOpened, cast(1 as decimal) CustomerId, ‘name’ CustomerName”; var item = connection.Query<ProductItem, Customer, ProductItem>(sql, (p, c) => { p.Customer = c; return p; }, splitOn: “CustomerId”).First(); item.Customer.CustomerId.IsEqualTo(1); The splitOn param needs to be specified as the split … Read more

Manually map column names with class properties

Dapper now supports custom column to property mappers. It does so through the ITypeMap interface. A CustomPropertyTypeMap class is provided by Dapper that can do most of this work. For example: Dapper.SqlMapper.SetTypeMap( typeof(TModel), new CustomPropertyTypeMap( typeof(TModel), (type, columnName) => type.GetProperties().FirstOrDefault(prop => prop.GetCustomAttributes(false) .OfType<ColumnAttribute>() .Any(attr => attr.Name == columnName)))); And the model: public class TModel { … Read more