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.







































Выездная бригада прибывает с необходимым оборудованием. Инфузионная терапия длится 60–120 минут; по ходу процедуры контролируются давление, пульс, дыхание и субъективное самочувствие, при необходимости схема корректируется (темп капания, смена растворов, добавление противорвотных или седативных средств). Чаще всего уже к концу первой инфузии снижается тошнота, уходит дрожь и «внутренняя дрожь», нормализуется сон. Врач оставляет пошаговый план на 24–72 часа: питьевой режим, щадящее питание (дробно, без жирного и острого), режим сна, рекомендации по витаминам и гепатопротекции. Если в процессе выявляются тревожные признаки (нестабильная гемодинамика, выраженная аритмия, спутанность сознания), будет предложен перевод в стационар.
Изучить вопрос глубже – вывод из запоя круглосуточно реутов
Crowngreen is a popular entertainment site that delivers exciting games for users. Crowngreen excels in the online gaming world and has gained reputation among visitors.
Every user at Crowngreen casino
can play top-rated slots and receive exciting bonuses. Crowngreen guarantees reliable gameplay, smooth transactions, and 24/7 customer support for all users.
With , gamers explore a huge variety of casino games, including classic options. The platform delivers entertainment and ensures a safe gaming environment.
Whether you are experienced or experienced, Crowngreen Casino guarantees something special for everyone. Sign up at Crowngreen today and experience rewarding games, fantastic bonuses, and a safe gaming environment.
Эта информационная статья содержит полезные факты, советы и рекомендации, которые помогут вам быть в курсе последних тенденций и изменений в выбранной области. Материал составлен так, чтобы быть полезным и понятным каждому.
Узнать больше > – https://bestmoby.ru/news-1003-poddergka-importa-kak-assotsiatsii-pomogayut-biznesu-na-megdunarodnoj-arene.html
Hi there, just became alert to your blog through
Google, and found that it is really informative. I am gonna watch out for brussels.
I will be grateful if you continue this in future.
Numerous people will be benefited from your writing.
Cheers!
Принтер Kyocera не печатает чёрным? В статье — замена узлов от сц
Because the admin of this website is working, no question very quickly it will be well-known, due to its quality contents.
https://volksmeter
Парогенератор Philips «свистит» или выдаёт ошибку? В статье — ремонт платы, помпы и других узлов от сервис
Как быстро запускается
Получить больше информации – бесплатная наркологическая помощь
Если на осмотре выявляются спутанность сознания, подозрение на делирий, неукротимая рвота с примесью крови, выраженная боль в груди, тяжёлая одышка, судороги — врач немедленно предложит стационар. Безопасность важнее удобства.
Получить дополнительную информацию – http://kapelnica-ot-zapoya-vidnoe7.ru
Срок действия (ориентир)
Подробнее – klinika-kodirovaniya-ot-alkogolizma
Hello there! Do you know if they make any plugins to assist with Search Engine Optimization? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good results. If you know of any please share. Many thanks!
https://notfaelleworms.de/
Эта информационная статья содержит полезные факты, советы и рекомендации, которые помогут вам быть в курсе последних тенденций и изменений в выбранной области. Материал составлен так, чтобы быть полезным и понятным каждому.
Продолжить чтение – https://yukinawa.ru/news-26787-pogarnyj-sertifikat-eto-ne-formalnost-a-garant-bezopasnosti-lyudej-i-imuschestva.html
Тепловизионный прицел Dali начал «глючить»? В статье — диагностика и устранение неисправностей. Прочитайте перед обращением в сц
Медикаментозное пролонгированное
Изучить вопрос глубже – https://kodirovanie-ot-alkogolizma-vidnoe7.ru/kodirovanie-ot-alkogolizma-na-domu-v-vidnom/
Этап
Узнать больше – https://vyvod-iz-zapoya-noginsk7.ru/vyvod-iz-zapoya-kruglosutochno-v-noginske
Прежде чем решать, где и как лечиться, важно соотнести текущее состояние с уровнем медицинского контроля. Таблица ниже помогает увидеть разницу между форматами и выбрать безопасный старт.
Подробнее – http://narkologicheskaya-pomoshch-orekhovo-zuevo7.ru/narkologicheskaya-pomoshch-na-domu-v-orekhovo-zuevo/
Hi it’s me, I am also visiting this website regularly, this site is in fact nice and the viewers are in fact sharing fastidious thoughts.
1xbet-sport.pro
Перед таблицей коротко поясним логику: мы выбираем самый безопасный маршрут именно для вашей ситуации, а при изменении состояния оперативно переключаемся на другой формат без пауз.
Получить больше информации – narkolog-vyvod-iz-zapoya
Перед началом терапии врач проводит осмотр, собирает анамнез, измеряет давление и сатурацию, при необходимости делает экспресс-тесты. На основании данных подбирается индивидуальная схема, рассчитываются объёмы инфузии и темп введения, оценивается необходимость кардиоконтроля.
Углубиться в тему – skoraya-pomoshch-vyvoda-iz-zapoya
Даже если кажется, что «пройдёт само», при запойных состояниях осложнения нарастают быстро. Перед списком отметим логику: показания к инфузионной терапии определяет врач по совокупности симптомов, хронических заболеваний и текущих показателей. Ниже — типичные ситуации, при которых капельница даёт предсказуемый клинический эффект и снижает риски.
Выяснить больше – вызвать капельницу от запоя на дому
Форматы помощи — состав и показания
Выяснить больше – https://narkologicheskaya-pomoshch-ramenskoe7.ru/narkologicheskaya-pomoshch-na-domu-v-ramenskom/
Если по ходу первичного осмотра выявляются «красные флаги» (спутанность сознания, нестабильное давление/ритм, кровавая рвота, подозрение на делирий), врач немедленно предложит госпитализацию и аккуратно организует перевод — безопасность всегда выше удобства.
Подробнее – психиатр нарколог на дом
90’lar modas?n? hat?rlayanlar burada m?? Sizlere gecmisin moda ikonu olan donemden ilhamla ipuclar? sundugumuz bu yaz?ya davetlisiniz.
Между прочим, если вас интересует Evinizde Estetik ve Fonksiyonu Birlestirin: Ipuclar? ve Trendler, загляните сюда.
Ссылка ниже:
https://anadolustil.com
Guzellik, gecmisle gunumuz aras?nda bir kopru kurmakt?r. 90’lar?n moda s?rlar?, bu koprunun onemli parcalar?ndan.
Этап
Узнать больше – анонимный вывод из запоя
Когда уместен
Исследовать вопрос подробнее – https://narkologicheskaya-pomoshch-orekhovo-zuevo7.ru/kruglosutochnaya-narkologicheskaya-pomoshch-v-orekhovo-zuevo/
Медикаментозное пролонгированное
Узнать больше – kodirovanie-ot-alkogolizma-vyezd-na-dom
Tarz?n?z? 90’lar?n unutulmaz modas?ndan esinlenerek gunumuze tas?mak ister misiniz? Oyleyse bu yaz?m?z tam size gore!
Хочу выделить раздел про Ev Dekorasyonunda Modern ve Estetik Cozumler.
Вот, можете почитать:
https://evimturk.com
Tarz?n?zda 90’lar?n esintilerini hissetmeye baslad?g?n?za eminim. Gecmisin izlerini tas?maktan korkmay?n!
Мы гарантируем полную анонимность и конфиденциальность на всех этапах лечения в «Детокс» в Краснодаре. Ваши личные данные не будут переданы третьим лицам, и вы не будете поставлены на учёт.
Выяснить больше – нарколог на дом вывод из запоя в краснодаре
Вывод из запоя на дому в Краснодаре — удобное решение для тех, кто не может посетить клинику. Наши специалисты приедут к вам домой, проведут необходимую диагностику и лечение.
Углубиться в тему – врач вывод из запоя
Эта обзорная заметка содержит ключевые моменты и факты по актуальным вопросам. Она поможет читателям быстро ориентироваться в теме и узнать о самых важных аспектах сегодня. Получите краткий курс по современной информации и оставайтесь в курсе событий!
Детальнее – https://seoflx.net/o/kdeea-rank-website-on-first-page
PlayAmo Site Web Betting Platform is one of the famous iGaming networks for gamblers who adore amusement, gifts, and swift transactions.
With hundreds of exceptional spinners, baccarat, and streamed tables, PlayAmo delivers a exclusive online trip right from your station or Android.
New users can enjoy generous intro offers, free spins, and unlock premium club rewards.
Whether you try old-school slots or the upcoming hits, PlayAmo Platform offers everything you need for exciting real gaming
https://gyn101.com/
gyn101.com
Эта познавательная публикация погружает вас в море интересного контента, который быстро захватит ваше внимание. Мы рассмотрим важные аспекты темы и предоставим вам уникальные Insights и полезные сведения для дальнейшего изучения.
Где почитать поподробнее? – https://blog1-c12882-1.bacagora.ac/video-sur-la-simulation-du-proces
Эта обзорная заметка содержит ключевые моменты и факты по актуальным вопросам. Она поможет читателям быстро ориентироваться в теме и узнать о самых важных аспектах сегодня. Получите краткий курс по современной информации и оставайтесь в курсе событий!
Запросить дополнительные данные – https://www.riferimenti.org/chiyodaku/kasumigaseki
An outstanding share! I have just forwarded this onto a colleague who was doing a little research on this. And he in fact ordered me lunch due to the fact that I stumbled upon it for him… lol. So let me reword this…. Thanks for the meal!! But yeah, thanx for spending some time to discuss this topic here on your internet site.
skla
Mac & Cheese strain
Very informative blog, highly recommended
Welcome to the Granescorts elite escort agency in Dubai!
Each client is immensely important to us, so for over 15 years we have been delighting you with the highest level of service, exclusive escort services and the largest and most up-to-date catalog of elite girls and TOP models.
A huge variety of the most Dubai luxury escort girls can be found only with us – blondes, brunettes, redheads, slim, curvy, fitness girls, athletes, photo models, nude models, porn models, famous girls from Instagram, as well as unique options – twins and even triplets! Therefore, with undisguised pride, we present you our TOP escort models! You can verify this right now by looking at the profile data or visiting the catalog page, which features the most beautiful and sexy girls from Dubai and beyond.
What i don’t realize is in reality how you are not actually a lot more neatly-liked than you might be right now.
You are very intelligent. You recognize thus significantly in the case of this matter, produced me individually believe it from a lot of various angles.
Its like men and women don’t seem to be fascinated unless it’s one thing to accomplish with Lady gaga!
Your personal stuffs great. Always take care of it up!
Hello colleagues
Hi. A 26 fine website 1 that I found on the Internet.
Check out this website. There’s a great article there. https://fuentitech.com/there-will-be-broadband-internet-on-the-moon/519531/|
There is sure to be a lot of useful and interesting information for you here.
You’ll find everything you need and more. Feel free to follow the link below.
Thanks very interesting blog!
Hi all, here every person is sharing these familiarity, therefore it’s good to read this weblog, and I used to pay a quick visit this blog all the time.
https://projp89.com/melbet-bukmekerskaya-kontora-skachat-na-ajfon/
Pretty! This was an incredibly wonderful article. Thank you for providing this information.
https://kitty168.com/kak-skachat-melbet-2025/
Nice post. I learn something totally new and challenging on blogs I stumbleupon everyday. It’s always helpful to read through articles from other authors and practice a little something from other sites.
https://maxwin98.net/melbet-obzor-2025/
Currently it sounds like Drupal is the preferred blogging platform out there right now. (from what I’ve read) Is that what you are using on your blog?
https://supriya.info/skachat-melbet-kazino-2025-obzor/
Hey! Do you know if they make any plugins to safeguard against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any suggestions?
https://amustsite.com/melbet-prilozhenie-obzor-2025/
Howdy are using WordPress for your blog platform? I’m new to the blog world but I’m trying to get started and create my own. Do you need any html coding knowledge to make your own blog? Any help would be really appreciated!
https://e-art.com.ua/chomu-dekoratyvni-masky-u-faru-staly-trendom-u-tiuninhu.html
Представьте, что помощь приходит прямо к вам: в квартире, где нужна поддержка. Детокс в Екатеринбурге реализует услугу вызова нарколога на дом, чтобы облегчить состояние пациента без транспортировки и лишнего стресса. Врач подключит капельницу, проведёт детоксикацию и даст рекомендации по восстановлению, всё это в вашем знакомом окружении.
Изучить вопрос глубже – вызов нарколога на дом екатеринбург
Hello i am kavin, its my first time to commenting anywhere, when i read this paragraph i thought i could also make comment due to this good paragraph.
https://kamen.dp.ua/yak-korpusy-fary-mozhut-zekonomyty-vam-hroshi-na-r.html
Superb, what a webpage it is! This webpage provides helpful information to us, keep it up.
https://mama-86.org.ua/instrumenty-dlia-far-shcho-vkhodyt-u-profesiini-nabory.html
Нет, чтобы решить тащить или нет твое устройство в сервисный центр, для начала попробуй по статье пройтись, если ничего не помогло, то уже сдавай в сервис
магазин интимных товаров премиум купить Секс-шоп Erross интим-магазин товаров для взрослых с анонимной доставкой по Москве и РФ.