Skip to content

Instantly share code, notes, and snippets.

@lancscoder
Created February 14, 2012 19:28
Show Gist options
  • Star 22 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save lancscoder/1829462 to your computer and use it in GitHub Desktop.
Save lancscoder/1829462 to your computer and use it in GitHub Desktop.
Dapper Getting Started
public class ConnectionFactory {
public static DbConnection GetOpenConnection() {
var connection = new SqlConnection("MyConnectionString");
connection.Open();
return connection;
}
}
// Dapper - Delete
using (var connection = MvcApplication.GetOpenConnection()) {
connection.Execute(@"delete from Posts where id = @id", new { id = 1 });
}
// Dapper – Filtered List
using (var connection = ConnectionFactory.GetOpenConnection()) {
var posts = connection.Query<Post>("select * from posts where text like @text", 
new { text = "%Some Value%" }).ToList();
}
// Dapper - Insert
using (var connection = MvcApplication.GetOpenConnection()) {
var post = new Post { 
Title = "Title 1", 
Text = "Text 1", 
PublishDate = DateTime.Now };
post.ID = connection.Query<int>(@"insert into Posts(Title, Text, PublishDate)
values (@Title, @Text, @PublishDate); 
select cast(scope_identity() as int)", 
new { post.Title, post.Text, post.PublishDate }).First();
}
// Dapper Insert Using SQL Compact Edition
using (var connection = MvcApplication.GetOpenConnection()) {
var post = new Post { 
Title = "Title 1", 
Text = "Text 1", 
PublishDate = DateTime.Now };
connection.Execute(@"insert into Posts(Title, Text, PublishDate)
values (@Title, @Text, @PublishDate);", 
new { post.Title, post.Text, post.PublishDate });
post.ID = (int)connection.Query(@"select @@IDENTITY as ID").First().ID;
}
// Dapper – Simple List
using (var connection = ConnectionFactory.GetOpenConnection()) {
var posts = connection.Query<Post>("select * from posts").ToList();
}
return new MvcMiniProfiler.Data.ProfiledDbConnection(connection, MiniProfiler.Current);
// Dapper - Single
using (var connection = MvcApplication.GetOpenConnection()) {
var post = connection.Query<Post>("select * from posts where id = @id", 
new { id = 1 }).First();
}
// Dapper - Update
using (var connection = MvcApplication.GetOpenConnection()) {
var post = connection.Query<Post>( 
"select * from posts where id = @id", new { id = 1 } ).First();
post.Title = "New Title";
connection.Execute(@"update Posts set Title = @Title, 
Text = @Text, PublishDate = @PublishDate where ID = @id;", 
new { post.ID, post.Title, post.Text, post.PublishDate });
}
@kzwr
Copy link

kzwr commented Jul 20, 2016

Thank You

@disklosr
Copy link

Thanks

@ChauThan
Copy link

I love it.
Thanks.

@nikosk84
Copy link

Very useful. Thanks.

@santosgabriel
Copy link

Thanks for the code! 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment