An experiment in supplementing the API material with video. This will be rough at first…
.NET APIs Part 5 – All the CRUD APIs
In the previous posting we saw how to create an API to get all the cars in our database. In this posting we’ll look at the remaining CRUD (Create Review Update Delete) operations.
As you may remember, we created a controller named CarController. ASP.NET will strip off the word Controller, leaving us with Car, which we will use to access the endpoints of our API.
An endpoint is just a URL that takes us to the operation we want.
We looked at GetAll, let’s take a look at Get. In this case, we have an id for the car we want, but we want all the details of that car. Simple!
.NET APIs Part 4 – Creating the APIs
We are, finally, ready to create our ASP.NET Core application that will host our traditional and our minimal APIs. (This series begins here.)
The code for this blog post is available here:
git clone https://github.com/JesseLiberty/Cars.git
Please note that WordPress seems to be broken and so the layout will be imperfect.
To get started, open Visual Studio 2022 and make sure you are fully up to date. Click on Create A New Project and select ASP.NET Core Web App, making sure that C# is the selected language
File Comparison
In a previous post I said I was still looking for the right file comparison tool. I may have found it! I returned to ExamDiff Pro and voilà! the perfect combination of power and ease of use. I integrated it with Visual Studio and life is good.
.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
Talking Unit Testing
I’m interviewed by my old friend J. Tower (of Trailhead Technology Partners) on his Blue Blazes YouTube program, talking about Unit Testing. Lots of fun discussing an important topic. Tune in here.
APIs in .NET – Part 2 – The Database
As noted in part 1 of this series, I will be building an application specifically to explore building APIs. To get started, I’ll want to build a back-end database. The application we’ll be simulating is a car dealership. Customers can list a car for sale, or look through cars they might buy.
We want to keep things very simple, so we will create a single table for now: Car
Car will have six columns
- id (int primary key)
- make (varchar 50)
- model (varchar 50)
- model_year (int)
- price (decimal)
- deleted (int)
By marking id as primary key you ensure two things: no two cars will have the same id, and each added row will have an incremented value. The deleted column allows us to have “soft” deletes — that is, we mark a row deleted but do not remove it from the table.
We can now insert a few rows:
insert into car
(make, model, model_year, price, deleted)
values ('Subaru', 'Imprezza', 2024 ,35500, 0),
('Subaru','Outback',2024,42000, 0),
('Prius','C',2022,25000, 0)
Note: I highly recommend the book SQL Pocket Guide (O’Reilly, Alice Zhao) for looking up how to do all the SQL operations I’ll show in these blog entries.
With this table, we can create endpoints for the CRUD (Create Read Update Delete) operations and more (e.g., obtaining a list of available vehicles).
In the next post, we’ll build our first endpoint to get a list of available cars.
New Series: Creating APIs in .NET
While I’m still happily ensconced at CNH Industrial, I have changed my job. I’m no longer writing mobile applications (for the first time in about 7 years!) but rather am writing APIs using ASP.NET Core and C#. -The plan is to have a book on creating APIs (how-to, best practices, patterns, etc.) next year. In the interim, I’ll be writing a series of blog posts covering such topics as how to get started, software and tools you’ll need, REST, and much more.
As part of this series, I’ll create a dead-simple real-world example of a car selling and buying application, suggested by Daniel Brevitt (technical editor of .NET MAUI For C# Programmers). This application will consist of four major parts:
- The backend SQL Server database
- The front end for administrators (for inventory, etc.)
- The front end for customers (for buying or selling)
- The API that connects the front end to the back end
We’ll create a very simple SQL database using SQL Server and SSMS, and take advantage of Dapper: a simple ORM (Object Relational Model). We will not cover Entity Framework as our focus will be on the APIs, not the back end.
Similarly, the front end will be a very simple application — though at first I’ll simply use Postman rather than building out the front end. In fact, given how important and powerful Postman is, I may never get around to building a real front-end. Getting familiar with the Postman is more important for our purposes.
We will build three types of APIs
- Traditional APIs built using controllers in ASP.NET Core and .NET 7/8
- Minimal APIs
- Azure Functions
My focus in the first posts will be on the first two types, so that we can work locally without having to use Azure for now (there are tools for working with Azure functions locally, but we’ll hold off on that). In fact, we’ll create such a simple database that you can recreate it locally (and I’ll put all the code for this series up on GitHub).
For these posts, I anticipate developing on Windows using:
- Visual Studio 2022
- C# – probably nothing more advanced than C# 7 or 8, though bits of later versions may appear from time to time
- SQL Server (latest)
- SQL Server Management Studio (SSMS) that comes with SQL Server
- Postman (latest)
- Dapper (latest)
- AutoMapper
All of the software we’ll be using is free (the community editions are fine).
In the next post I’ll create the database and its preliminary tables.
11th MVP award
Pleased and proud to have been awarded my 11th MVP award from Microsoft.
Hey! I was interviewed on WebRush
I had the pleasure of turning the tables and being interviewed on WebRush with Jon Papa et al
https://www.webrush.io/episodes/episode-240-theres-something-net-maui-with-jesse-liberty