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.







































buy prescription drugs from india: Flexi Meds India – online pharmacy no prescription
References:
Hard rock casino cleveland https://www.hulkshare.com/sudangrape92/
http://fleximedsindia.com/# india pharmacy
http://easynorthrxs.com/# canadian pharmacy
References:
Club regent casino https://mattiehblx507363.blogozz.com/40349078/casino-of-gold-dein-ultimativer-guide
References:
Jack and the beanstalk games https://shaunarvkt443673.wizzardsblog.com/41494845/casino-of-gold-dein-ultimativer-guide
References:
Du mobile dubai https://merritt-fink-5.technetbloggers.de/ubersicht-der-einzahlungsmoglichkeiten
MexiCare Direct: MexiCare Direct – MexiCare Direct
http://mexicaredirect.com/# farmacia mexicana en chicago
magnific.com
http://mexicaredirect.com/# mexican online pharmacy
https://www.magnific.com/search?format=search&last_filter=query&last_value=meilleur+code+promo+1win+burkina+faso%3A+1W2026VIP+%E2%80%93+500%25+%2B+Free+Spins&query=meilleur+code+promo+1win+burkina+faso%3A+1W2026VIP+%E2%80%93+500%25+%2B+Free+Spins
Tive uma intuição com o Candy Bonanza no fim de semana e batata: o triplo do depósito de lucro.
Hey there! Do you use Twitter? I’d like to follow you if that would be okay. I’m undoubtedly enjoying your blog and look forward to new posts.
indian pharmacy online: top 10 pharmacies in india – top online pharmacy
Easy North RX: Easy North RX – Easy North RX
If some one wants expert view about running a blog then i suggest him/her to pay a visit this webpage, Keep up the good job.
Enjoyed reading through this, very good material. Thanks!
india pharmacy: Flexi Meds India – best online pharmacy
There are a lot of different ways to approach this kind of topic, but the direction you chose to take makes the information feel very accessible, which is something I always look for when browsing through articles online.
site de paris sportif hors arjel
https://mexicaredirect.com/# mexico prescriptions
http://fleximedsindia.com/# indianpharmacy com
https://www.magnific.com/search?format=search&last_filter=query&last_value=code+promo+1win+gratuit+togo%3A+1W2026VIP+%E2%80%93+500%25+D%C3%A9p%C3%B4t&query=code+promo+1win+gratuit+togo%3A+1W2026VIP+%E2%80%93+500%25+D%C3%A9p%C3%B4t
想把综艺区入口单独留着时先保留这张入口页整页翻起来更舒服顺手综艺更新片库
best online pharmacy india: Flexi Meds India – secure medical online pharmacy
https://www.magnific.com/search?format=search&last_filter=query&last_value=1Win+Free+Promo+Code%3A+1W2026VIP+%E2%80%93+Free+Bonus+Bangladesh&query=1Win+Free+Promo+Code%3A+1W2026VIP+%E2%80%93+Free+Bonus+Bangladesh
There is something really appealing about the way this post presents its ideas, since it keeps the reader interested from beginning to end while also leaving enough room for people with different opinions to think about the topic and share their own perspective thoughtfully.
casino en ligne avec retrait immediat
http://easynorthrxs.com/# canadian pharmacies that deliver to the us
https://www.magnific.com/search?format=search&last_filter=query&last_value=%E0%A6%AD%E0%A6%BE%E0%A6%B0%E0%A6%A4+%E0%A6%8F+1Win+%E0%A6%93%E0%A6%AF%E0%A6%BC%E0%A7%87%E0%A6%B2%E0%A6%95%E0%A6%BE%E0%A6%AE+%E0%A6%AC%E0%A7%8B%E0%A6%A8%E0%A6%BE%E0%A6%B8+%E0%A6%95%E0%A7%8B%E0%A6%A1%3A+1W2026VIP+%E2%80%93+%E0%A6%AB%E0%A7%8D%E0%A6%B0%E0%A6%BF+%E0%A6%AC%E0%A7%8B%E0%A6%A8%E0%A6%BE%E0%A6%B8&query=%E0%A6%AD%E0%A6%BE%E0%A6%B0%E0%A6%A4+%E0%A6%8F+1Win+%E0%A6%93%E0%A6%AF%E0%A6%BC%E0%A7%87%E0%A6%B2%E0%A6%95%E0%A6%BE%E0%A6%AE+%E0%A6%AC%E0%A7%8B%E0%A6%A8%E0%A6%BE%E0%A6%B8+%E0%A6%95%E0%A7%8B%E0%A6%A1%3A+1W2026VIP+%E2%80%93+%E0%A6%AB%E0%A7%8D%E0%A6%B0%E0%A6%BF+%E0%A6%AC%E0%A7%8B%E0%A6%A8%E0%A6%BE%E0%A6%B8
http://easynorthrxs.com/# Easy North RX
reputable canadian pharmacy: Easy North RX – canadian pharmacies compare
Easy North RX: Easy North RX – Easy North RX
This post presents the ideas clearly and respectfully, creating a discussion that feels positive and enjoyable for readers.
bookmaker hors arjel
http://mexicaredirect.com/# MexiCare Direct
This is the kind of post that works well for a variety of readers because it stays straightforward, balanced, and enjoyable without trying too hard, which makes it easier for readers with different points of view and opinions to stay involved in the conversation.
Bet Way
скачать vpn 2026
临时想刷分类片库先把这页固定住看片前少走弯路追更热门片单频道
https://mexicaredirect.com/# mexican pharmacies online drugs
stromectol ivermectin 3 mg how much is ivermectin stromectol 0.5 mg
Информационная статья о гейминге
как сделать секс игрушку
Мужик на час – это доступная услуга для ликвидации бытовых сбоев в городе. Когда перестал работать лампочка, не стоит выносить выходных. Универсальные мастера прибегут молниеносно по всему дому.
Коллеги, начинаю разговор наболевший для огромного количества вопрос. Как отобрать опытного профессионала? По результатам наблюдений советую обратить внимание к услуге Универсальный мастер. Это никоим образом не сиюминутное решение, а индустрия услуг домашнего обслуживания.
При каких проблемах актуален Муж на час Москва?
Область применения чрезвычайно широк. Ограничусь хитов сезона:
Быстрый ремонт. Когда внезапно засорился слив. Муж на час по первому звонку приедет.
Сборка и запуск домашней техники. Ждет подключения детскую кроватку? Запрещается рисковать. Гарантированный исполнитель установит ровно безупречно и быстро.
Сервис по монтажу тяжелого оборудования. Установить кондиционер идеально ровно — это специальность для Мастер на час Москва.
Urgent ремонтные работы. Затопило соседей? Лицензированный техник готов ко всему.
Главные преимущества привлечения профессионала
Как доказано этого способа? Все логично:
1. Сохранение драгоценного времени. Вы освобождаетесь от драгоценные часы на попытки решить. Сертифицированный техник решает мгновенно за полчаса.
2. Качество и гарантия. Стажер 10+ лет гарантирует письменно. Вы спокойны.
3. Профессиональный арсенал. Отпадает необходимость в дрель аккумуляторную. Специалист приезжает вооруженный.
4. Профессиональная безопасность. Сантехника, проводка, газ — это не область для гаражного ремонта. Привлекайте профессионалов.
Резюмируя хочу подчеркнуть: услуга Мастер на час — это не роскошь, а проверенное решение для городского профессионала, который осознает ценность времени. С уверенностью рекомендую активировать этим вариантом.
Какое преимущество выбрать Помощник на час?
Разнообразный палитра работ: до сантехнических работ.
Экспресс-доставка мастера без дополнительных расходов на МКАД в том числе выезд за пределы.
Прайс-лист адекватные – начиная 1500 ?/час.
Надёжность на все виды услугу минимум 1 года.
Круглосуточный режим диспетчерская.
Какие сервисные услуги предлагает Мастер на час Москва?
Сантехника: Замена душевых систем; разбор течи.
Электрика: Регулировка эл.щитового оборудования; выявление неисправностей.
Мебель и интерьер: Ремонт полок.
Двери и замки: Замена дверных систем.
Другое: Фиксация громоздкой техники.
Формируйте заявку без промедления! Линк. Мастерская – центральный федеральный округ.
Мужик на час – ваш мастер на все руки в ситуации любой случай.
Доверьтесь проверенным профи Муж на час в Москве в городе. Гарантия доказано восхищенными профессионализмом жителей столицы.
Наш центр оказывает помощь при запое на дому, амбулаторно и в стационаре. Врач нарколог приезжает по адресу, проводит осмотр, оценивает физическое и психическое состояние пациента, подбирает препараты, ставит капельницу, дает рекомендации после процедуры и помогает выбрать дальнейшее лечение алкоголизма.
Изучить вопрос глубже – вывод из запоя вызов на дом
What I like most here is the clear and thoughtful structure of the post, because it keeps the information organized and easy to follow while still allowing the discussion to feel easygoing, natural, and engaging for different readers.
Virsavia косметология
Aw, this was an extremely good post. Spending some time and actual effort to create a really good article… but what can I say… I hesitate a lot and don’t manage to get anything done.
ivermectin 500ml Clinical Pharmacology and Safety Profiles of Stromectol stromectol 3 mg price
semaglutide with insurance Advancing Clinical Research in Metabolic Health and Weight Management
does medicare cover semaglutide for weight loss liraglutide
I like how this post manages to keep the discussion both simple and valuable at the same time, because the overall presentation feels clear, well-rounded, and interesting enough to keep readers interested all the way through the conversation.
цена Empower RF
Thanks for your post on this blog site. From my experience, there are times when softening right up a photograph could possibly provide the wedding photographer with an amount of an inspired flare. Oftentimes however, that soft cloud isn’t just what you had planned and can frequently spoil an otherwise good image, especially if you intend on enlarging the item.
Вызов нарколога на дом в Казани. Круглосуточная наркологическая помощь на дому: лечение запоя, детоксикация, капельница, консультация. Анонимный прием. Узнайте цену в клинике.
Получить больше информации – нарколог на дом вывод казань