.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. Fiit Jazz Only Fans Leaked Fansly Leaks Mega Folder Download Link ( https://UrbanCrocSpot.org )

  2. NamiSwanBB – NamiBBSwan Only Fans Leaked Fansly Leaks Mega Folder Download Link ( https://UrbanCrocSpot.org )

  3. Tatted Baddie Only Fans Leaked Fansly Leaks Mega Folder Download Link ( https://UrbanCrocSpot.org )

  4. Ms Biddies Only Fans Leaked Fansly Leaks Mega Folder Download Link ( https://UrbanCrocSpot.org )

  5. Soriyah Sann Only Fans Leaked Fansly Leaks Mega Folder Download Link ( https://UrbanCrocSpot.org )

  6. Baddiee Babe Only Fans Leaked Fansly Leaks Mega Folder Download Link ( https://UrbanCrocSpot.org )

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

  8. Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?

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

  10. NaturalLuvsBeauty – The Comfy Princess – LiaMirandaLinzy Only Fans Leaked Fansly Leaks Mega Folder Download Link ( https://UrbanCrocSpot.org )

  11. Russian Creammmmmm – TheySayyPassionnx Only Fans Leaked Fansly Leaks Mega Folder Download Link ( https://UrbanCrocSpot.org )

  12. I Am Queen Jaii FANSLY Only Fans Leaked Fansly Leaks Mega Folder Download Link ( https://UrbanCrocSpot.org )

  13. Destiny Next Door Only Fans Leaked Fansly Leaks Mega Folder Download Link ( https://UrbanCrocSpot.org )

  14. Kyoko Akihiro Only Fans Leaked Fansly Leaks Mega Folder Download Link ( https://UrbanCrocSpot.org )

  15. Wir sind stolz, sämtliche Standards und Anforderungen des Glücksspielstaatsvertrages zu erfüllen und dir so ein sicheres und reguliertes Spiel zu
    ermöglichen. Wer nach einer Online Spielothek sucht, die nicht nur
    schnelle, sondern auch sichere Zahlungsmethoden anbietet, ist bei LeoVegas genau richtig.
    Jedes Automatenspiel wird von unseren Slot-Expterten sorgfältig ausgewählt und getestet, um sicherzugehen,
    dass dir mit jedem Slot das beste Spielerlebnis geboten wird.
    Im Vergleich zu Online Spielotheken ohne deutsche Lizenz bieten wir dir nicht
    nur eine regulierte und sichere Basis für dein Slot-Spiel, sondern wir können auch steuerfreie Gewinne
    gewährleisten.
    Der gesamte Prozess ist sicher, effizient und darauf
    ausgelegt, dass Sie schnell spielen können. Sie können dann Ihre erste Einzahlung
    tätigen, Ihren Willkommensbonus beanspruchen und direkt in die beeindruckende Bibliothek
    von Slots, Tischspielen und Live-Casino-Erlebnissen eintauchen. Der Zusatz
    “online” steht dafür, dass du sie über das Internet spielen kannst, also über im Grunde jedes “smarte” Endgerät, welches mit
    dem Internet verbunden ist.
    Bei LeoVegas glauben wir daran, unseren Spielern mehr
    für ihr Geld zu bieten. Man weiß nie, woher das nächste Lieblingsspiel oder der größte Gewinn kommen könnte!
    Außerdem bieten viele dieser Spiele zugängliche
    Einstiegspunkte, was sie sowohl für erfahrene Wetter als
    auch für Neueinsteiger perfekt macht. Genießen Sie
    die spannende Welt der Spielautomaten verantwortungsbewusst und denken Sie daran, dass Glücksspiel immer unterhaltsam sein sollte.
    Wir stellen Tools und Ressourcen zur Verfügung, die
    Ihnen helfen, Ihr Spiel zu verwalten, um sicherzustellen, dass
    Ihr Erlebnis unterhaltsam und innerhalb Ihrer Grenzen bleibt.
    Für diejenigen, die günstige Quoten schätzen, bieten wir auch eine Auswahl
    an Slots mit hoher RTP (Return to Player), die Ihnen langfristig eine bessere theoretische Rendite bieten.

    References:
    https://online-spielhallen.de/posido-casino-mobile-app-dein-mobiles-spielvergnugen/

  16. Amira X Evans Only Fans Leaked Fansly Leaks Mega Folder Download Link ( https://UrbanCrocSpot.org )

  17. Krissy Taylor VIP Only Fans Leaked Fansly Leaks Mega Folder Download Link ( https://UrbanCrocSpot.org )

  18. Claudia G Only Fans Leaked Fansly Leaks Mega Folder Download Link ( https://UrbanCrocSpot.org )

  19. Robyn Banks VIP Only Fans Leaked Fansly Leaks Mega Folder Download Link ( https://UrbanCrocSpot.org )

  20. Great site, i recommend it to everyone ArbSwap

  21. Besonders attraktiv sind der Willkommensbonus, der Winshark no deposit bonus sowie wechselnde Aktionen mit Freispiele-Angeboten.
    Dennoch solltest du dir deinen bis zu 2.000€ High Roller Bonus oder unseren exklusiven 125% Ersteinzahlungsbonus nicht entgehen lassen. Das Online Casino mag zwar
    einen geringeren Willkommensbonus von nur 500€ anbieten, kann dafür aber
    mit einem umfassenden VIP-Programm punkten, und dessen Status auch ausschlaggebend für deinen wöchentlichen Casino Cashback Bonus ist.
    In unserer WinShark Erfahrung sind wir auf eine gute
    Balance aus Live Casino Spielen und Tisch- und Kartenspielen gestoßen. Durch deine
    gesammelten Punkte kannst du dir im Shop dann entsprechende
    Belohnungen in Form von Freispielen oder einem Guthaben kaufen.
    Die Marke hat sich schnell einen soliden Ruf für Zuverlässigkeit, Transparenz und spielerorientierte Richtlinien aufgebaut.
    Spieler, die ausschließlich in lizenzierten deutschen Casinos spielen möchten, sollten zu Alternativen greifen. Mit über
    6000 Spielen von namhaften Anbietern wie Play’n GO, Pragmatic Play und NetEnt bietet die Plattform
    eine bemerkenswerte Bandbreite digitaler Automatenspiele.
    Wir erklären Ihnen, was Glücksspieler motiviert und warum dieses Hobby nicht zu
    Reichtum führen wird.

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

  23. Great site, i recommend it to everyone ArbSwap

  24. SpookySwap's avatar SpookySwap says:

    SpookySwap FantomI personally find that the interface is reliable uptime, and I enjoy checking analytics here.

  25. SpookySwap financeI personally find that the interface is reliable uptime, and I enjoy checking analytics here.

  26. OnlyFans Accounts W Balance

  27. OnlyFans Account With Balance

  28. Mariatogel's avatar Mariatogel says:

    I switched from another service because of the wide token selection and great support.

  29. togelup's avatar togelup says:

    Taylor here — I’ve tried learning crypto basics and the reliable uptime impressed me.

  30. togelup's avatar togelup says:

    This platform exceeded my expectations with low fees and easy onboarding.

  31. Goltogel's avatar Goltogel says:

    I was skeptical, but after a week of using the mobile app, the easy onboarding convinced me. The dashboard gives a complete view of my holdings.

  32. Mariatogel's avatar Mariatogel says:

    I personally find that shawn here — I’ve tried swapping tokens and the useful analytics impressed me.

  33. The cross-chain transfers tools are low fees and trustworthy service.

Leave a Reply

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