.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

** Note ** Jesse is currently looking for a new position. You can learn more about him at https://jesseliberty.bio Thank you. 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. His latest book, Building APIs with .NET, is now available wherever you buy your books. Liberty 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 13 year Microsoft MVP.
This entry was posted in API, Essentials. Bookmark the permalink.

363 Responses to .NET APIs Part 3 – Dapper

  1. dewapoker's avatar dewapoker says:

    I’ve been active for a month, mostly for learning crypto basics, and it’s always intuitive UI.

  2. I personally find that the interface is useful analytics, and I enjoy checking analytics here.

  3. ierc10arr6's avatar ierc10arr6 says:

    GREAT BLOG, I HAVE UNDERSTAND REALLY MUCH BECAUSE YOU JUST WRITTEN EXTREMELY FANTASTIC BLOG.
    바카라사이트 추천

  4. Goltogel's avatar Goltogel says:

    The using the API process is simple and the intuitive UI makes it even better. My withdrawals were always smooth.

  5. dewapoker's avatar dewapoker says:

    The testing new tokens process is simple and the reliable uptime makes it even better. Great for cross-chain swaps with minimal slippage.

  6. V88toto's avatar V88toto says:

    I personally find that i’ve been using it for a week for portfolio tracking, and the reliable uptime stands out.

  7. Royaltoto's avatar Royaltoto says:

    The interface is easy onboarding, and I enjoy swapping tokens here. The updates are frequent and clear.

  8. V88toto's avatar V88toto says:

    The site is easy to use and the clear transparency keeps me coming back. I moved funds across chains without a problem.

  9. Royaltoto's avatar Royaltoto says:

    I’ve been using it for a year for using the API, and the scalable features stands out. Support solved my issue in minutes.

  10. Royaltoto's avatar Royaltoto says:

    I personally find that the site is easy to use and the robust security keeps me coming back. Support solved my issue in minutes.

  11. TK88's avatar TK88 says:

    Hello! Quick question that’s completely off topic. Do you know how to make your site mobile friendly? My web site looks weird when browsing from my iphone 4. I’m trying to find a theme or plugin that might be able to resolve this problem. If you have any suggestions, please share. Cheers!

  12. tile2lite0's avatar tile2lite0 says:

    THIS IS A GREAT ARTICLE AND I AM VERY INTERESTING TO READ THIS, THANKS!
    메이저사이트

  13. you could have a terrific blog right here! would you like to make some invite posts on my blog?

  14. Your point of view caught my eye and was very interesting. Thanks. I have a question for you. https://www.binance.com/en/register?ref=JHQQKNKN

  15. OF Creator Account Fully Verified

  16. linetogel's avatar linetogel says:

    Would you be curious about exchanging hyperlinks?

  17. Hometogel's avatar Hometogel says:

    Everyone loves what you guys are usually up too. This sort of clever work and reporting! Keep up the wonderful works guys I’ve included you guys to blogroll.

  18. OnlyFans Accounts W Balance

  19. With everything which seems to be building within this specific area, many of your perspectives tend to be rather radical. Nevertheless, I beg your pardon, because I can not give credence to your whole theory, all be it exhilarating none the less. It would seem to everyone that your remarks are generally not entirely rationalized and in simple fact you are your self not even wholly certain of the assertion. In any event I did appreciate reading it.

  20. I carry on listening to the newscast talk about getting boundless online grant applications so I have been looking around for the top site to get one. Could you tell me please, where could i find some?

  21. I liked as much as you will receive performed right here. The sketch is tasteful, your authored subject matter stylish. nonetheless, you command get got an shakiness over that you want be handing over the following. in poor health undoubtedly come more beforehand again as precisely the similar just about a lot ceaselessly inside case you protect this hike.

  22. OF Creator Account Fully Verified

  23. OnlyFans Accounts W Balance

Leave a Reply

Your email address will not be published. Required fields are marked *