Dapper .Net

Summary

A commenter on my blog mentioned Dapper .Net so I decided to take a look.  Dapper is known as a Micro-ORM.  It’s very easy to get started and can be used as a stepping stone between non-ORM code and an ORM with LINQ queries.  First, I’ll show how it’s done:


Installing Dapper in Visual Studio

I created a console application in Visual Studio 2012, then I opened the NuGet package manager and searched for Dapper.  Just install the NuGet package:



Writing the Code

In your usings, you’ll need to add the “using Dapper;” and you’ll also need to add “using System.Data.SqlClient;”.  The actual database connection will be the standard SqlClient .net methods.  Here’s the basic code I wrote for my console application:

private static string ConnectionString = “server=sqlservername;Trusted_Connection=yes;database=sampledata;Integrated Security=true;“;

static void Main(string[] args)
{
    using (var db = new SqlConnection(ConnectionString))
    {
        db.Open();

        var query = db.Query<Store>(“SELECT * FROM store“);

        foreach (var item in query)
        {
            Console.WriteLine(“Name:“+item.Name);
        }

        Console.ReadKey();
    }
}


I also had to create a class for “Store”, which dapper will map the result set to:

namespace DapperDotNetDemo
{
    public class Store    {
        public int id { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Zip { get; set; }
        public string text { get; set; }
    }
}


That’s it.  As you can see, the LINQ part of this ORM is not used.  Instead a query is used just like any other ADO database access method.  The ORM portion of this is the return set.  Technically, the return class can be used in a LINQ query.


Summary

I’m going to go deeper into this subject in a future blog post, but for now, I just wanted to introduce Dapper for anybody that has not heard of it or Micro-ORMs.  If you want more examples of how to use Dapper you can follow one of these links:

Dapper .Net
A Look at Dapper .Net
Dapper .Net by Example

 
 

 

Leave a Reply