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!
First we need a method in our controller:
[HttpGet("{id}")]
public async Task<ActionResult<Car>> Get(int id)
{
var car = await _carRepository.Get(id);
if (car == null)
{
return NotFound();
}
return car;
}
Notice that next to the HttpGet attribute we indicate that the endpoint will take the id of the car we want
[HttpGet("{id}")]
This means we need to modify the URL to access the endpoint by adding the actual id of the desired record.
The first thing we do is call the repository, passing in the id.
public async Task<Car?> Get(int id)
{
var query = "select * from car where id=@id";
using var db = databaseConnectionFactory.GetConnection();
return await db.QuerySingleOrDefaultAsync<Car>(query, new {id});
}
In the Get method of the repo we create our query, get our connection and execute the query returning the value we retrieved (if any). This is very close to what we did previously.
Back in the controller, we check to ensure that we received a Car. If not, we return NotFound which is a shorthand way of returning a 404 message. Otherwise we return the Car as a Json object. You can see this in Postman:
We’ll issue a Get command passing in the URL, ending with the id of the car we want (in this case 4)
Notice that we get back a 200, indicating success. In the body of the returned Json we get back all the details of the Car. (If you decide to use DTOs you can get whatever subset of the information makes sense):
Post
Adding a Car to the database is quite similar. We need a method in the controller and one in the repo. Here is the controller method:
[HttpPost]
public async Task<ActionResult<Car>> Post([FromBody] Car car)
{
try
{
car = await _carService.Insert(car);
}
catch (Exception e)
{
return BadRequest(e);
}
return CreatedAtAction(nameof(Get), new { id = car.Id }, car);
}
Look at the attribute in the parameter ([FromBody]. This indicates to the API that the data needed to insert this Car will be in the body of the call. The alternative is FromQuery. You can, in fact, use both in one call.
Note: CreatedAction causes a return code of 201, which is what we want. Here’s the body we’ll insert:
When we click Send this data is sent to the API which returns 201 (created) and in the body of the returned data we see the new id assigned to this car
Service Class
Notice that this time, instead of calling the Repo directly, the method in the controller calls into a service class. A service class is a great way to get the logic out of the controller, where it does not belong, without putting it into the repo, where it also does not belong.
Here’s the top of the CarService
public class CarService : ICarService
{
private readonly ICarRepository _carRepository;
public CarService(ICarRepository carRepository)
{
_carRepository = carRepository;
}
public async Task<Car> Insert(Car car)
{
var newId = await _carRepository.UpsertAsync(car);
if (newId > 0)
{
car.Id = newId;
}
else
{
throw new Exception("Failed to insert car");
}
return car;
}
All the logic associated with this insert (e.g., making sure we get back a legitimate id from the repository, etc.) is encapsulated in the service.
This leaves the repository free to just talk to the database,
public async Task<int> UpsertAsync(Car car)
{
using var db = databaseConnectionFactory.GetConnection();
var sql = @"
DECLARE @InsertedRows AS TABLE (Id int);
MERGE INTO Car AS target
USING (SELECT @Id AS Id, @Name AS Name, @Model_Year AS Model_Year,
@Is_Deleted AS Is_Deleted, @Origin AS origin ) AS source
ON target.Id = source.Id
WHEN MATCHED THEN
UPDATE SET
Name = source.Name,
Model_Year = source.Model_Year,
Is_Deleted = source.Is_Deleted,
Origin = source.Origin
WHEN NOT MATCHED THEN
INSERT (Name, Model_Year, Is_Deleted, Origin)
VALUES (source.Name, source.Model_Year,
source.Is_Deleted, source.Origin)
OUTPUT inserted.Id INTO @InsertedRows
;
SELECT Id FROM @InsertedRows;
";
var newId = await db.QuerySingleOrDefaultAsync<int>(sql, car);
return newId == 0 ? car.Id : newId;
}
Rather than having an insert and an update method, we combine that logic into this upsert method. This is a common idiom for database manipulation.
Note: to make this work, be sure to fill in all the fields for a car (or at least as many as you want to have in the Database.
Delete
As noted earlier, we will implement a soft delete; that is, rather than actually removing the data from the database, we’ll just set the is_deleted column to true. This allows us to reverse the action, and make the row not-deleted by simply changing that value to false.
[HttpDelete(“{id}”)]
public async Task<IActionResult> Delete(int id)
{
try
{
await _carService.Delete(id);
}
catch (Exception e)
{
return BadRequest(e);
}
return NoContent();
}
As you would expect, the endpoint takes an id (the id of the car we want to delete). The controller then hands that off to the service, which calls the repository which, in turn, marks that id as deleted:
public async Task<int> DeleteAsync(int id)
{
using var db = databaseConnectionFactory.GetConnection();
var query = "UPDATE car SET Is_Deleted = 1 WHERE Id = @Id";
return await db.ExecuteAsync(query, new { Id = id });
}
If you are comfortable with SQL none of this will be very surprising. The key walkaway is:
Summary
In this post we saw that endpoints are just URLs with (potentially) data in the body of the request. The controller handles the URL and in our case passes the id or other data to the service. The service handles the (business) logic and then delegates talking to the database to the repository.
Book
This posting is excerpted from my forthcoming book Building APIs with .NET and C# to be released next year by Packt.







































liraglutide pharmacy semaglutide
cheap liraglutide Advancing Clinical Research in Metabolic Health and Weight Management
tirzepatide https://usobesityscience.org/tirzepatide-analysis/ generic liraglutide
rybelsus patient assistance program us obesity science
Hi, i think that i noticed you visited my web site thus i came to return the favor?.I am attempting to find things to improve my website!I assume its ok to make use of some of your ideas!!
This post combines a friendly tone with a well-organized format, making the content comfortable and clear for readers.
Академия доктора Стар
diabetes medications rybelsus tirzepatide
В данной публикации мы поговорим о процессе восстановления от зависимости, о том, как вернуть себе нормальную жизнь. Мы обсудим преодоление трудностей, значимость поддержки и наличие программ реабилитации. Читатели смогут узнать о ключевых шагах к успешному восстановлению.
Не упусти шанс – Похмельная служба Краснодар
weight loss on rybelsus orlistat
Your method of explaining the whole thing in this paragraph is really fastidious, every one be able to simply know it, Thanks a lot.
how long has rybelsus been on the market American Metabolic Research Institute
It’s appropriate time to make some plans for the future and it’s time to be happy. I’ve read this post and if I could I desire to suggest you few interesting things or suggestions. Maybe you can write next articles referring to this article. I want to read more things about it!
This article provided exactly the kind of direct information I was hoping to find today. Your neutral breakdown of the facts makes the whole subject highly accessible.
free spins no deposit
I enjoy how this post keeps the discussion insightful and relaxed at the same time because it makes the overall content more interesting to read.
free spins no deposit
rybelsus stock AMRI
This is a great tip especially to those fresh to the blogosphere. Short but very accurate info… Thanks for sharing this one. A must read post!
Вы получаете не просто разовую процедуру, а комплекс медицинской помощи. Врач нарколога может объяснить родственникам, как говорить с зависимым, что делать после капельницы, какие препараты принимать, когда необходимо лечение в клинике и почему кодирование алкоголизма или реабилитация часто становятся следующим этапом. Такой подход помогает не только вывести пациента из запоя, но и начать полноценное восстановление.
Узнать больше – наркологический вывод из запоя казань
Thanks for the auspicious writeup. It if truth be told was a leisure account it. Look complicated to more introduced agreeable from you! However, how can we be in contact?
Your writing flows very clearly, and the transition between the different points you raised was smooth enough that I found myself reading through the entire post without getting distracted or losing my place even once.
free spins no deposit
semaglutide https://usobesityscience.org/glp-1-agonists/ liraglutide price
liraglutide online American Metabolic Research Institute
buy victoza tirzepatide
Важно не ждать, когда состояние пациента станет критическим. Алкоголизма, наркомании и других форм зависимости часто стесняются, но промедление может привести к осложнениям, депрессии, агрессии, нарушению работы органов, тяжелой интоксикации и риску для жизни человека.
Углубиться в тему – narkolog-na-dom-kazan20.ru/
Great beat ! I would like to apprentice while you amend your web site, how can i subscribe for a blog site? The account helped me a acceptable deal. I had been a little bit acquainted of this your broadcast provided bright clear idea
Новогодние праздники для детей в Екатеринбурге
Запой опасен не только похмелья и слабостью. При запойным употреблении нарушается сон, повышается тревожность, страдает печень, сердце, сосудистая система, желудка и поджелудочной железы. Потеря контроля, очередной прием спиртного и сильная тягу к алкоголю могут приводить к белой горячки, психоза, судороги, инфаркт или инсульта.
Выяснить больше – наркологический вывод из запоя в казани
Your article helped me a lot, is there any more related content? Thanks!
https://diocesiugento.org/pgs/horoshie_manery.html
Regards, Helpful information! https://www.instapaper.com/read/1995856153
Howdy! I understand this is sort of off-topic however I had to ask. Does managing a well-established blog like yours require a lot of work? I am brand new to writing a blog however I do write in my diary daily. I’d like to start a blog so I will be able to share my personal experience and views online. Please let me know if you have any recommendations or tips for brand new aspiring bloggers. Thankyou!
If you are going for finest contents like myself, simply pay a visit this web page every day for the reason that it offers quality contents, thanks
Hi there friends, how is the whole thing, and what you desire to say regarding this article, in my view its really amazing for me.
I was suggested this website by my cousin. I’m not sure whether this post is written by him as nobody else know such detailed about my problem. You are wonderful! Thanks!
Heya i’m for the first time here. I came across this board and I find It really useful & it helped me out a lot. I hope to give something back and aid others like you aided me.
За более чем 20 лет работы мы зарекомендовали себя как надежный партнер в сфере пассажирских перевозок, обслужив тысячи довольных клиентов. Наша миссия — обеспечить максимальный комфорт, абсолютную безопасность и строгую пунктуальность каждой поездки. https://images.google.ge/url?q=https://avtobus.dp.ua/kontakty/
I am not sure where you are getting your information, but great topic. I needs to spend a while finding out more or figuring out more. Thank you for wonderful info I was in search of this information for my mission.
References:
Choctaw casino https://ttym.space/bernadetteh70/avalon-ii-slot2004/wiki/Avalon-II-On-Crown-of-Egypt-%241-deposit-the-internet-Slot-Review-2026-Newmeasures%2C-a-Denison-Consulting-practice
Heya! I realize this is sort of off-topic however I needed to ask. Does managing a well-established blog such as yours require a massive amount work? I am completely new to blogging but I do write in my journal everyday. I’d like to start a blog so I can share my personal experience and thoughts online. Please let me know if you have any kind of recommendations or tips for brand new aspiring bloggers. Thankyou!
adult xxx video porn site xxx sex video
Hey there, You’ve done an incredible job. I will certainly digg it and personally suggest to my friends. I’m sure they will be benefited from this web site.
Bookmaker sans limite de mise
buy cialis pill http://mensrxguide.org/# Tadalafil Tablet
cialis for sale MensRxGuide – Cialis over the counter
Define o alvo antes de abrir Bikini Paradise. Bateu, sai. Não tem negociação.
I don’t even know how I ended up right here, but I thought this post was once great. I do not know who you’re however definitely you’re going to a famous blogger if you happen to are not already. Cheers!
Amazing! This blog looks just like my old one! It’s on a entirely different topic but it has pretty much the same layout and design. Excellent choice of colors!
I’m impressed, I have to admit. Rarely do I come across a blog that’s both equally educative and engaging, and without a doubt, you have hit the nail on the head. The issue is something which too few folks are speaking intelligently about. I’m very happy that I came across this in my search for something relating to this.
Generic Tadalafil 20mg price MensRxGuide – Buy Tadalafil 20mg
My spouse and I stumbled over here different website and thought I might check things out. I like what I see so now i am following you. Look forward to checking out your web page again.
Cialis over the counter MensRxGuide – Cheap Cialis
Лечение хронического алкоголизма начинается с купирования абстинентного синдрома, после чего проводятся мероприятия по нормализации работы печени, сердечно-сосудистой и нервной системы. Назначаются гепатопротекторы, ноотропы, витамины группы B. Также проводится противорецидивная терапия.
Получить дополнительные сведения – наркологические клиники алкоголизм ярославль
I am really grateful to the owner of this site who has shared this enormous article at at this time.