Dapper.NET

Getting started with Dapper.NET

Remarks#

What is Dapper?

Dapper is a micro-ORM for .Net that extends your IDbConnection, simplifying query setup, execution, and result-reading.

How do I get it?

Common Tasks

Versions#

VersionNotesRelease Date
1.50.0core-clr / asp.net 5.0 build against RTM2016-06-29
1.42.02015-05-06
1.40.02015-04-03
1.30.02014-08-14
1.20.02014-05-08
1.10.02012-06-27
1.0.02011-04-14

Install Dapper from Nuget

Either search in the Visual Studio GUI:

Tools > NuGet Package Manager > Manage Packages for Solution… (Visual Studio 2015)

screenshot of the Visual Studio package manager interface with Dapper being selected

Or run this command in a Nuget Power Shell instance to install the latest stable version

Install-Package Dapper

Or for a specific version

Install-Package Dapper -Version 1.42.0

Using Dapper in C#

using System.Data;
using System.Linq;
using Dapper;

class Program
{
    static void Main()
    {
        using (IDbConnection db = new SqlConnection("Server=myServer;Trusted_Connection=true"))
        {
            db.Open();
            var result = db.Query<string>("SELECT 'Hello World'").Single();
            Console.WriteLine(result);
        }
    }
}

Wrapping the connection in a Using block will close the connection

Using Dapper in LINQPad

LINQPad is great for testing database queries and includes NuGet integration. To use Dapper in LINQPad press F4 to open the Query Properties and then select Add NuGet. Search for dapper dot net and select Add To Query. You will also want to click Add namespaces and highlight Dapper to include the Extension Methods in your LINQPad query.

Once Dapper is enabled you can change the Language drop down to C# Program, map query results to C# classes, and use the .Dump() method to inspect the results:

void Main()
{
	using (IDbConnection db = new SqlConnection("Server=myServer;Trusted_Connection=true")){
		db.Open();
		var scalar = db.Query<string>("SELECT GETDATE()").SingleOrDefault();
		scalar.Dump("This is a string scalar result:");
		
		var results = db.Query<myobject>(@"
		SELECT * FROM (
		VALUES (1,'one'),
			(2,'two'),
			(3,'three')
		) AS mytable(id,name)");
		results.Dump("This is a table mapped to a class:");
	}
}

// Define other methods and classes here
class myobject {
	public int id { get; set; }
	public string name { get; set; }
}

The results when executing the program would look like this:

LINQPad screenshot


This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow