.NET APIs Part 3 – Dapper

In part 2 of this series we created a simple database. In this part we’ll look at how to perform CRUD operations against that DataBase in anticipation of creating APIs for these operations.

Dapper is a micro-ORM (Object Relational Mapper) for .NET that simplifies data access against a database. In this blog post, we’ll focus on a code example that employs Dapper to manage a Car entity. This example uses a custom DatabaseConnectionFactory to handle database connections. Let’s dive right in.

​Database configuration

You will need a working MS Sql database running to test the code. In the sample code, you can set your connections details in the appsettings.json file.

​Create the database and car table

​Create your database and then you can use the following script to initialize the database

USE [Cars]
GO
/****** Object:  Table [dbo].[car] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[car](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[make] [varchar](50) NULL,
	[model] [varchar](50) NULL,
	[model_year] [int] NULL,
	[price] [decimal](18, 0) NULL,
	[deleted] [int] NULL,
 CONSTRAINT [add_identity] PRIMARY KEY CLUSTERED
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO

Required NuGet Packages

​We are using the following NuGet packages:

​- Dapper
- Dapper.SqlBuilder

​You can install these packages using the NuGet Package Manager Console:

​Install-Package Dapper
Install-Package Dapper.SqlBuilder

Setting Up the Database Connection Factory

​Before we get into the CarRepository class, let’s discuss the DatabaseConnectionFactory class. This class is responsible for creating and opening database connections. It leverages DbSettings to get the connection string:

​DatabaseConnectionFactory takes an IOptions<DbSettings> dependency, which allows it to read the database settings from a configuration source (like appsettings.json). The GetConnection method uses this information to create and open a SQL Server connection, which it then returns.

​The Car Repository

​Initialization and Dependency Injection

​The CarRepository class takes a DatabaseConnectionFactory as a constructor argument, indicating dependency injection:

Methods in Car Repository

​GetAll Method

​This method returns all the car records. Optionally, it can also return records marked as deleted.

The GetAll method uses Dapper.SqlBuilder to construct the SQL query dynamically. This allows for more flexibility, as you can conditionally add WHERE clauses, joins, or other SQL constructs.

Get Method

​This method retrieves a single car record based on its ID:

UpsertAsync Method

​The UpsertAsync method handles both insert and update operations:

DeleteAsync Method

​The DeleteAsync method marks the record as deleted:

Resources

​Dapper GitHub Repository 
Dapper SqlBuilder

​ Conclusion

​Dapper offers a powerful, yet simple way to perform CRUD operations in .NET applications. The code example in this post demonstrates how to make the most of Dapper in a practical scenario involving a Car entity. The DatabaseConnectionFactory class helps to manage database connections efficiently, ensuring that the rest of the code can focus on business logic rather than connection management. Whether you need to build SQL queries dynamically or perform simple operations, Dapper has tools to help you get the job done efficiently.


Rodrigo Juarez is a full-stack developer who has specialized in Xamarin in recent years and is now focusing on MAUI.
He is also a book author. With over 25 years of experience, Rodrigo has contributed to a diverse array of projects, developing applications for web, desktop, and mobile platforms. Specialized in Microsoft technologies, he has expertise across various sectors, including management, services, insurance, pharmacy, and banking. Rodrigo Juarez can be reached at info@rodrigojuarez.com

Unknown's avatar

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. Liberty is a Senior AI Engineer at the University of Pittsburgh Medical Center, and was a Team Lead and Senior Software Engineer for various corporations, a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a 21 year Microsoft MVP.
This entry was posted in API, Essentials. Bookmark the permalink.

363 Responses to .NET APIs Part 3 – Dapper

  1. Block chain's avatar Block chain says:

    Good job on this article! Good job on this article! I really like your article. Great post! Have you ever heard of s8e8 s8e8? You appear to know a lot about this. Got sucked into your site forabout the last few minutes. I enjoyed your post. Thank you. I really like your article. I kind of find that funny for some weird reason. Got sucked into your post forabout the last few hours. Great read. Thanks for writing this. You appear to know a lot about this. Got sucked into your insight forabout the last few minutes. You appear to know a lot about this. It’s like you wrote the book on it or something.

  2. rikvipforum's avatar rikvipforum says:

    Thanks for the sensible critique. Me & my neighbor were just preparing to do a little research on this. We got a grab a book from our local library but I think I learned more from this post. I am very glad to see such great info being shared freely out there.

  3. Jesse Grillo's avatar Jesse Grillo says:

    You’ve made my day! Thx again. You appear to know a lot about this. Your article has proven useful to me. I would like to say excellent blog!

  4. Free Chloral's avatar Free Chloral says:

    This is an excellent, an eye-opener for sure!

  5. I truly appreciate this post. You are obviously very knowledgeable. Are there any well researched articles on the subject or any closely related subjects? And once again, you are king.

  6. Dear email's avatar Dear email says:

    Interesting content.

  7. s8e8 s8e8's avatar s8e8 s8e8 says:

    You appear to know a lot about this. It is a strange thing I believed I was a pro on the topic before reading this blog but it turns out, I’m still a student. I really like your article. I really like your article.

  8. This information is magnificent. It’s like you read my thoughts! I enjoyed reading this. I enjoyed reading what you had to say.

  9. con artist's avatar con artist says:

    Thumbs up! I enjoyed reading what you had to say. Nice read. You’ve made my day! Thx again.

  10. Full refund's avatar Full refund says:

    Thanks for writing this. Interesting content. Good job on this article! You are a very persuasive writer.

  11. buy crypto's avatar buy crypto says:

    I never discovered any other post like this. I enjoyed reading this. Some nice points there. You really should doing what you are doing awesome content similar to this one . Compare rates? Nice write up. Ever been to Arkansas? Some nice points there. I enjoyed your post. Thank you. Great post! Really Cool. It’s like you wrote the book on it or something. Hit me up! I’ve found any other points like yours. Google Plus pros would agree with your blogs. I really like your article. You really need to keep doing what you are doing awesome stuff like this one !

  12. cheap price's avatar cheap price says:

    You’ve made my day! Thx again. Great read. Hit me up! You are a very persuasive writer. The people at product page are a fake website. Great read. You’ve made my day! Thx again. I really like your article. This might give me a chance to check out what else is happening in the world. I really like your article. I enjoyed reading what you had to say. Some nice points there. You appear to know a lot about this. You’ve made my day! Thx again. I enjoyed your post. Thank you. Great read. You are a very persuasive writer.

  13. One time's avatar One time says:

    You’ve made my day! Thx again. Hit me up! Your article has proven useful to me. This is an excellent, an eye-opener for sure! delmain delmain. I enjoyed reading what you had to say. I really like your article. This is an excellent, an eye-opener for sure! Some nice points there. You appear to know a lot about this. Your article has proven useful to me. Wow, that sure is a smart way of wording it. Good job on this article! You are obviously very knowledgeable. Your article has proven useful to me. This information is magnificent. Nice read.

  14. 야코's avatar 야코 says:

    I’m in awe of the author’s ability to make complicated concepts approachable to readers of all backgrounds. This article is a testament to his expertise and dedication to providing valuable insights. Thank you, author, for creating such an engaging and enlightening piece. It has been an absolute pleasure to read!

  15. Pretty great post. I just stumbled upon your blog and wished to mention that I have really enjoyed browsing your blog posts. After all I will be subscribing to your rss feed and I am hoping you write once more very soon!

  16. Your point of view caught my eye and was very interesting. Thanks. I have a question for you. https://accounts.binance.info/it/register/person?ref=P9L9FQKY

  17. I have observed that online diploma is getting favorite because getting your degree online has become a popular alternative for many people. A huge number of people have definitely not had a possible opportunity to attend a regular college or university but seek the elevated earning possibilities and a better job that a Bachelor’s Degree gives you. Still other people might have a qualification in one discipline but want to pursue some thing they now possess an interest in.

  18. GemstoneRO Servers is one of the best Ragnarok Online private servers in 2026, offering two free RO servers: Renewal with EP21 Age of Heroes, chapter 1, chapter2 4th jobs, Doram, latest skills and mid rates, and Loki Pre-Renewal with classic gameplay, custom quests, unique gear and 100x rates. Play on PC or Android with an active global community, low-latency proxies, weekly updates and no paytowin. Join GemstoneRO and enjoy Ragnarok Online your way.

  19. One thing I’ve noticed is the fact there are plenty of beliefs regarding the financial institutions intentions if talking about foreclosure. One misconception in particular is the bank desires your house. The bank wants your hard earned money, not your house. They want the funds they lent you with interest. Avoiding the bank will simply draw a new foreclosed summary. Thanks for your posting.

  20. I think this is among the most vital info for me. And i am glad reading your article. But should remark on few general things, The web site style is wonderful, the articles is really great : D. Good job, cheers

  21. Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.

  22. Wow, fantastic blog layout! How long have you ever been running a blog for? you made running a blog glance easy. The entire look of your website is wonderful, let alone the content!

  23. Buy Proxies's avatar Buy Proxies says:

    It’s arduous to seek out educated folks on this matter, but you sound like you know what you’re talking about! Thanks

  24. I’m just commenting to let you be aware of of the fantastic discovery our daughter found reading the blog. She came to understand lots of details, including what it is like to have a marvelous coaching style to have folks just know just exactly chosen extremely tough matters. You truly surpassed our own desires. Thank you for rendering the informative, dependable, educational as well as cool thoughts on that topic to Ethel.

  25. I value the stable performance and low fees. This site is reliable.

  26. Backlinks's avatar Backlinks says:

    One thing I’ve noticed is there are plenty of beliefs regarding the finance institutions intentions any time talking about foreclosed. One misconception in particular is the fact the bank needs to have your house. Your banker wants your dollars, not your house. They want the amount of money they gave you having interest. Keeping away from the bank will undoubtedly draw any foreclosed summary. Thanks for your write-up.

  27. I visited a lot of website but I conceive this one has something extra in it in it

  28. woh I like your content, saved to bookmarks! .

  29. Juliana x Ferrara Only Fans Leaked Fansly Leaks Mega Folder Download Link ( https://UrbanCrocSpot.org )

  30. Paradis Only Fans Leaked Fansly Leaks Mega Folder Download Link ( https://UrbanCrocSpot.org )

  31. Minx Millz Only Fans Leaked Fansly Leaks Mega Folder Download Link ( https://UrbanCrocSpot.org )

  32. YouDreamofShayy Only Fans Leaked Fansly Leaks Mega Folder Download Link ( https://UrbanCrocSpot.org )

Comments are closed.