Thursday, April 07, 2011

Dapper - a simple object mapper for .Net

Features
Dapper is a single file you can drop in to your project that will extend your IDbConnection interface.
It provides 3 helpers:

Execute a query and map the results to a strongly typed List
public static List<T> ExecuteMapperQuery<T>(this IDbConnection cnn, string sql, object param = null, SqlTransaction transaction = null)

Example usage:

public class Dog
{
    public int? Age { get; set; }
    public Guid Id { get; set; }
    public string Name { get; set; }
    public float? Weight { get; set; }
    public int IgnoredProperty { get { return 1; } }
}            
            
var guid = Guid.NewGuid();
var dog = connection.ExecuteMapperQuery<Dog>("select Age = @Age, Id = @Id", new { Age = (int?)null, Id = guid });
            
dog.Count()
    .IsEqualTo(1);
dog.First().Age
    .IsNull();
dog.First().Id
    .IsEqualTo(guid);

Execute a query and map it to a list of dynamic objects
public static List<dynamic> ExecuteMapperQuery (this IDbConnection cnn, string sql, object param = null, SqlTransaction transaction = null)
This method will execute SQL and return a dynamic list.

Example usage:
 var rows = connection.ExecuteMapperQuery("select 1 A, 2 B union all select 3, 4");
((int)rows[0].A)
   .IsEqualTo(1);
((int)rows[0].B)
   .IsEqualTo(2);
((int)rows[1].A)
   .IsEqualTo(3);
((int)rows[1].B)
    .IsEqualTo(4);

Execute a Command that returns no results
public static int ExecuteMapperCommand(this IDbConnection cnn, string sql, object param = null, SqlTransaction transaction = null)

Read more: Google code