Spring.NET- Dapper micro ORM support

Here is code which shows how to extend Spring.NET’s AdoTemplate to enable Dapper micro ORM support. It is based on code & configuration presented in THIS post.

public delegate T DataContextDelegate<T>(DataContext command);
public delegate T IDbConnectionDelegate<T>(IDbConnection connection, IDbTransaction transaction);

public class ExtendedAdoTemplate : AdoTemplate
{
    public virtual T Execute<T>(IDbConnectionDelegate<T> del)
    {
        ConnectionTxPair connTxPair = ConnectionUtils.GetConnectionTxPair(DbProvider);

        return del(connTxPair.Connection, connTxPair.Transaction);
    }

    public virtual T Execute<T>(DataContextDelegate<T> del)
    {
        ConnectionTxPair connTxPair = ConnectionUtils.GetConnectionTxPair(DbProvider);

        using (var context = new DataContext(connTxPair.Connection))
        {
            context.Transaction = connTxPair.Transaction as DbTransaction;

            return del(context);
        }
    }
}

Usage example (imaginary reporting service):

[Transaction(IsolationLevel.ReadUncommitted, ReadOnly = true)]
public void RunReport(ReportInput input, Stream outputStream)
{
    var reportData = LinqAdoTemplate.Execute(delegate(IDbConnection conn, IDbTransaction tran)
    {
        var multi = conn.QueryMultiple("GetReport", param: input, transaction: tran, commandType: CommandType.StoredProcedure);

        var reportData1 = multi.Read<ProjectData1Row>()
            .ToList();
        var reportData2 = multi.Read<ProjectData2Row>()
            .ToList();
        var reportData3 = multi.Read<ProjectData3Row>()
            .ToList();

        return new
        {
            ProjectsInfo = reportData1,
            ProjectsMoreInfo = reportData2,
            ProjectsEvenMoreInfo = reportData3
        };
    });

    GeneratePDF(
        reportData.ProjectsInfo,
        reportData.ProjectsMoreInfo,
        reportData.ProjectsEvenMoreInfo,
        outputStream);
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: