This article is a series on using Dapper in .NET Core. Feel free to jump around, but we highly recommend you start in Part 1 and work your way through!
Part 1 – The What/Why/Who
Part 2 – Dapper Query Basics
Part 3 – Updates/Inserts/Deletes
Part 4 – Dapper Contrib
For some time now I’ve been a huge fan of using Dapper in both personal and commercial projects. With more and more projects lending themselves to Microservices architecture, or at the very least a large application being made up of many smaller components, Dapper just makes sense.
But I’m getting a little tired of telling the same story of what Dapper is and what it’s capable of doing, so here’s my attempt at a “crash course” in Dapper with .NET Core.
What Is Dapper?
Dapper is classed as a “micro” ORM. That is, it’s an ORM but is extremely lightweight and gives only very basic functionality. Whereas we might class something like Entity Framework or NHibernate as a fully featured heavyweight ORM, Dapper provides minimal overhead and really only helps you out with some core basics.
Put simply, it runs your database queries from your .NET Core code, and returns results in an easy to manage fashion.
Why Dapper?
The core reason people tend to pick Dapper over something like Entity Framework is the control it affords. Under Dapper, gone are the days of using a long complex LINQ queries that generate ghastly SQL that would make any DBA shriek at first sight. Infact, with Dapper you know exactly what SQL is going to be executed…. because you wrote it. As an example, if I have a “Event” table where I want to get the “EventName” of the record with an “Id” of 1. That would look like :
static void Main(string[] args) { var connectionString = "Data Source=(local);Initial Catalog=DapperExample;Integrated Security=SSPI"; using (SqlConnection connection = new SqlConnection(connectionString)) { var eventName = connection.QueryFirst<string>("SELECT TOP 1 EventName FROM Event WHERE Id = 1"); Console.WriteLine(eventName); Console.ReadLine(); } }
No ambiguity here, I know exactly what’s going to get run.
But that probably leads us to the question of “When should I NOT use Dapper“. And it’s actually a pretty good question. Realistically I think there are two types of developers/projects that mean that Dapper may not be on the cards.
The first is if you are thinking of moving an existing project to Dapper, and that project already makes heavy use of things like EntityTracking in Entity Framework – or really any Entity Framework specific feature, then Dapper may be a stretch. There is no entity tracking to speak of in Dapper – atleast out of the box (It’s all just POCO’s), so if you are expecting some of that EF magic, Dapper isn’t for you.
The second is actually developer specific and I debate if I should even put this in here. When trying to teach junior developers Dapper, they get annoyed that they have to write raw SQL. Personally I think if you are interacting with a database at all you should know SQL to a pretty high degree. But some developers really are just happy using the LINQ they already know and love, and for some the learning curve of ASP.NET Core is large enough without adding in databases to the mix. If that’s you, and you are just getting started with C# and don’t want to learn SQL just yet, then yeah, maybe this isn’t for you.
Who Is Behind Dapper?
The brains behind Dapper are the guys over at StackOverflow. It was created because the burden on the web servers of simply taking the LINQ2SQL statements and generating SQL was often making their web boxes hit 100% CPU. Coupled with the fact that you couldn’t actually control what SQL was output from your LINQ, Dapper was born.
Best of all, Dapper is completely open source. That means you can go check out how things work, and even fix bugs if you feel that way inclined!
Next Time
So with our history lesson out of the way, let’s actually get stuck in and write some simply Dapper statements. Click here to get cracking on Querying With Dapper.
Regarding “they get annoyed that they have to write raw SQL,” I think this is really short sighted. There are tons of reasons to avoid writing SQL in code. With tightly coupling code to a DB schema (when we want an abstraction here) at the top of the list, the entire concept of Code First is a big reason too. It’s just needlessly confrontational to assume that the only people who avoid raw sql strings in application code are “junior” devs. I strongly suggest removing that part.
I disagree (of course), but like the comment none the less.
I agree with you George. In order to optimize and have full control of the queries, raw SQL is always needed. Changes to SQL queries can be changed without changing the code. Adding raw SQL string in code is a security issue and will always be. Ofcourse, this may not be an issue for smaller internal projects.
RAW inline sql is junior at best and should be discouraged. Thirty years of coding has taught me that in-line sql in your code will create a massive headache down the line when you have to go back and support it!
>RAW inline sql is junior at best
Ironic that it’s built by StackOverflow who are the kings of helping juniors!
I’m not so sure it should be discouraged. It’s still a level of abstraction from ADO.NET, but IMO, a bigger thing to discourage is overselecting which I think is all too easy in heavy ORMs such as EF.
Imagine if you had an edit time tool that could verify that your query matched the database while you were editing your code.
For example, https://github.com/Zaid-Ajaj/Npgsql.FSharp.Analyzer
Thanks you for this article Wade.
I agree with your reasoning. Luckily the world isn‘t black or white. It‘s a matter of picking the right tool for the job, which also involves the developer‘s needs and (possible lack of) knowledge.
Personally, I very much like to be in control of my SQL DM. Also I use stored procedures instead of inline SQL code, which takes care of the security concerns mentioned above. Proper encapsulation/abstraction isn‘t a matter of choosing EF over Dapper or vice versa, but properly implementing OOP principles and other reasonings that suit the task at hand.
What I like about Dapper is its simplicity, speed and direct approach over EF.