Using Dapper Asynchronously in
Using Dapper Asynchronously in
CATEGORIES
My team is nally embarking on a new project that we can use
ABOUT ME
ASP.NET Core for. I've also been waiting a long time to use the
SPEAKING ENGAGEMENTS "micro-ORM" Dapper in one of our projects, and this new one ts
the bill: we need incredible performance and minimal coding.
Recent Posts
The Repository-Service Pattern with DI
and ASP.NET Core So what happens when the winds of change meet the waves of hope? You get
Joining the Dark (Mode) Side
mixed-up nautical imagery! And, hopefully, some insight into ASP.NET Core.
Bucket Sort - The Sorting Algorithm
Family Reunion
In this post, we're going to create a very simple ASP.NET Core 2.1 application
Radix Sort - The Sorting Algorithm
Family Reunion which uses Dapper to access data. There's already a sample project worked up
Gnome Sort - The Sorting Algorithm over on GitHub, and you might want to use that to follow along here.
Family Reunion
Featured Posts With all of that said, let's climb aboard the tutorial Titanic!
The Repository-Service Pattern with DI
and ASP.NET Core
Keep in Touch!
Twitter
GitHub
Subscribe via email Hmmmm. Maybe that wasn't the best metaphor.
Since this is an async implementation, note the use of the Task<> class (and refer
to an earlier article of mine for a refresher on how async and await keywords
work in ASP.NET.
}
}
We also need to update our project's Startup le to include our new repository in
the services layer:
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
Next, we need to enable this repository to use Dapper. Before we can do that,
however, we need it to be aware of what connection string we are using.
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"ConnectionStrings": {
"MyConnectionString": "MyConnectionString"
}
}
The problem is: how do we pass that connection string to the repository so it can
create a SqlConnection object for Dapper to use?
ASP.NET Core introduces a new IConfiguration object which can be injected into
other classes. That injected instance will contain a method called
GetConnectionString which we can use to obtain our connection string from the
appSettings.json les. So, let's inject IConfiguration like so:
Step 5: Employee by ID
Let's rst create a method to return employees by their ID.
To start, let's remember that the way Dapper works is by processing raw SQL and
then mapping it to an object. Because our table columns and object properties
share the same names, we don't need to do any special mapping here.
[Route("api/[controller]")]
[ApiController]
public class EmployeeController : ControllerBase
{
private readonly IEmployeeRepository _employeeRepo;
[HttpGet]
[Route("{id}")]
public async Task<ActionResult<Employee>> GetByID(int id)
{
return await _employeeRepo.GetByID(id);
}
[HttpGet]
[Route("dob/{dateOfBirth}")]
public async Task<ActionResult<List<Employee>>> GetByID(DateTime dateOfBirth)
{
return await _employeeRepo.GetByDateOfBirth(dateOfBirth);
}
}
Summary
That's it! We've implemented Dapper into our ASP.NET Core 2.1 application! Take
a look at the sample project over on GitHub if you want to see the whole thing.
With this infrastructure in place, using Dapper throughout the rest of my team's
project should be a breeze. Or, at least, we hopefully won't encounter any project-
sinking icebergs. All aboooooard!
Did I miss something about ASP.NET Core, Dapper, or anything else in this
tutorial? Did you take my sample project and make it better? I want to hear about
it! Sound o in the comments!
Happy Coding!
Matthew Jones
I'm a husband, father, developer, speaker, blogger, lots of things! Buy me a coffee
LOG IN WITH
OR SIGN UP WITH DISQUS ?
Name
And you can also do this which also adds to the maintainability of the application (then you know your query param
matches your actual query:
9△ ▽ • Reply • Share ›
https://github.com/bbsimonb...
http://fsprojects.github.io...
△ ▽ • Reply • Share ›
I don't understand why IDbConnection needs to be opened in the repository like above. I would have used below
code in ConfigureServices and then injected IDbConnection into repository/controller and used it that way. There is
no need to open SqlConnection as dapper would handle it for you.
Just grab your DbContext and get the connection from there.
It's nice to us EF Core for the simple stuff and insert/update ops, then use Dapper to map your complex queries. EF
Core seems to be weak at that IMHO.
△ ▽ • Reply • Share ›
Async method
[HttpGet]
[Route("{id}")]
public async Task<actionresult<employee>> GetByID(int id)
{
return await _employeeRepo.GetAsyncByID(id);
}
Sync method
[HttpGet]
[Route("{id}")]
public ActionResult<employee> GetByID(int id)
{
return _employeeRepo.GetByID(id);
}
Async will not freeze the main thread but then how does it make any difference when there is no UI
△ ▽ • Reply • Share ›
As far as I know you don't need to dispose dbConnection nor do you need to explicitly open it. Dapper does this all for
you. This is true for simple queries, for more complex one where you have more than one query doing the job and
with transactions in the mix then its better to open dbConnection by yourself where you need it, and close/dispose of
it where appropriate.
△ ▽ • Reply • Share ›
I understand that the authors have other projects they are working on so I'm not too upset with them. Just a bit
disappointed that one of the more popular ORMs out there in .NET is a bit dead in the water as far as active new
development goes.
△ ▽ • Reply • Share ›
Also, here's a couple of videos from a couple of years ago on what SO does.
https://groupby.org/confere...
△ ▽ • Reply • Share ›
Thanks again!
△ ▽ • Reply • Share ›
this way, you won't have to write again and again select query strings
△ ▽ • Reply • Share ›
1△ ▽ • Reply • Share ›
1△ ▽ • Reply • Share ›
Ten Seconds, Identity, and 20% Memory Loss: Why A Definitive FizzBuzz Solution Guide in C#
You Need Backups 25 comments • 7 months ago
4 comments • 4 months ago Whiteknight — I find another purpose for FizzBuzz in
Wellspring — It's probably some cardinal sin to reply to Avatarparticular is that it helps to weed out some people on the
Avatarthree blog posts with one comment, but I other end of the spectrum with a tendency to over-
(a) appreciated your post regarding outrage --> I think
Insertion Sort in C# - Exception Not Found Patience, Outrage Culture, and Mr. Berger's Class
3 comments • 3 months ago 8 comments • 9 months ago
James Curran — It should be noted the an Insertion Sort is Matthew Jones — I'm going to use the comments to
Avatarvery efficient on a linked-list (which allows O(1) insertions Avatarinclude a few details that I believe are relevant but that
into the middle of the list, rather than the O(n) required for didn't fit into the main story.1. There is no evidence that Mr.
✉ Subscribe d Add Disqus to your siteAdd DisqusAdd 🔒 Disqus' Privacy PolicyPrivacy PolicyPrivacy
dapper
Dapper vs Entity Framework vs ADO.NET Performance Benchmarking
1 post →
SWAGGER STORIES