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.

Cabinet IQ Austin
2419 S Bell Blvd, Cedar Park,
TX 78613, United Ѕtates
+12543183528
3Dmodeling
Неполадка с вашим устройством серьезная, но попробуйте по этой ссылке пройтись и поискать специализированный сервисный центр
Hello, every time i used to check weblog posts here in the early hours in the break of day, for the reason that i like to learn more and more.
https://admtmo.ru/forum/?PAGE_NAME=profile_view&UID=779
Pretty element of content. I just stumbled upon your blog and in accession capital to assert that I get actually enjoyed account your weblog posts. Anyway I will be subscribing in your augment or even I success you get admission to constantly quickly.
https://fontanero.com.ua/
AVIFtoPNGHero.com is a free converter for turning next-generation AVIF images into high-quality PNG files. As the web adopts the efficient AVIF format, this tool provides a simple way to ensure your images are viewable on older browsers and systems that lack support. The conversion process preserves crucial details, including transparency, making it ideal for web graphics and icons. Simply drag and drop your AVIF files, convert entire batches at once, and download your compatible PNGs in seconds. The service is entirely browser-based, requires no installation, and automatically deletes all files to guarantee your privacy.
aviftopnghero
PNGtoWebPHero.com is a utility for encoding PNG (Portable Network Graphics) images into the WebP format. The tool provides developers with control over the encoding process to optimize web assets. Users can select the compression mode – either lossless, which uses advanced techniques to reduce file size without data loss, or lossy, which uses predictive coding to achieve much greater file size reduction. For lossy encoding, a quality factor can be specified to manage the trade-off between file size and visual fidelity. The service correctly handles the PNG alpha channel, preserving transparency in the final WebP output. All processing is server-side, and data is purged after conversion.
pngtowebphero
4M Dental Implant Center
3918 Ꮮong Beach Blvd #200, Long Beach,
CA 90807, United Ꮪtates
15622422075
braces
LuckyMax https://server-test.momilash.com/online-casino-nederlan-u-lieve-va-lucky-max-casino-nu//
316439 488356You produced some decent points there. I looked on the net to the issue and discovered a lot of people go together with together along with your internet website. 216177
Hello! Do you know if they make any plugins to help with Search Engine Optimization? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good gains. If you know of any please share. Appreciate it!
kra40cc вход
LuckyMax NL https://www.arasgrupinsaat.com/offlin-gokhuis-nederlan-beste-legale-casinos-luckymax-casino-voor-2024/
LuckyMax NL https://server-test.momilash.com/online-casino-nederlan-u-lieve-va-lucky-max-casino-nu/
Компания «РБТ-Сервис» — профессиональный ремонт стиральных машин в СПб !
Для записи на ремонт и консультации посетите группу ВК: vk.com/remont_stiralnyh_mashin_spb_top
Качественный ремонт стиральных машин в СПб выполняют опытные мастера с многолетним стажем. Ремонт стиральных машин СПб включает диагностику, замену запчастей и настройку техники любой марки. Если требуется срочный ремонт стиральных машин — специалисты приезжают в день обращения.
– Гарантия до 2 лет
– Оригинальные запчасти
– Выезд по всему Санкт-Петербургу
Ремонт стиральных машин
LuckyMax Casino https://maatravels.co/allen-legale-luckymax-nederlandse-online-casinos-betreffende-mandaat-2024/
WebPtoJPGHero converter is an online image converter built for speed, simplicity, and accessibility. This web-based platform allows instant conversion of popular image formats such as PNG, WebP, and BMP into JPG files. No downloads, installations, or user accounts are required. The entire process happens in-browser and takes only a few seconds. Users can upload up to 20 files at once for batch conversion, making it suitable for individuals and professionals managing multiple images. All uploaded files are automatically deleted after processing to maintain privacy and ensure data security. WebPtoJPGHero is compatible with all modern devices, including desktops, tablets, and smartphones, offering flexibility for work on the go. Whether the goal is to reduce image file size, prepare visuals for the web, or standardize a project’s image format, this tool delivers clean, reliable results without any extra steps.
WebPtoJPGHero
JPG Hero converter is an online image converter built for speed, simplicity, and accessibility. This web-based platform allows instant conversion of popular image formats such as PNG, WebP, and BMP into JPG files. No downloads, installations, or user accounts are required. The entire process happens in-browser and takes only a few seconds. Users can upload up to 20 files at once for batch conversion, making it suitable for individuals and professionals managing multiple images. All uploaded files are automatically deleted after processing to maintain privacy and ensure data security. JPGHero.com is compatible with all modern devices, including desktops, tablets, and smartphones, offering flexibility for work on the go. Whether the goal is to reduce image file size, prepare visuals for the web, or standardize a project’s image format, this tool delivers clean, reliable results without any extra steps.
JPGHero
Unlock your images with WebPtoJPGHero.com, the simple, free solution for solving WebP compatibility issues. While the WebP format helps websites load faster, it can leave you with files you can’t easily edit or share. Our online tool provides an instant fix, transforming any WebP image into a high-quality JPG that works seamlessly across all your devices and applications. You can fine-tune the output quality to balance clarity and file size, and even save time by converting an entire batch of photos at once. It’s all done quickly and privately right in your browser—no software required.
WebPtoJPGHero.com
Excellent article. Keep writing such kind of information on your page. Im really impressed by your site.
Hello there, You have done an excellent job. I will definitely digg it and individually suggest to my friends. I am confident they will be benefited from this website.
Vegastars casino
87253 197974I want to start a blog written by a fictitious character commenting on politics, current events, news etc..How?. 427823
155954 917718If you are nonetheless on the fence: grab your favorite earphones, head down to a Best Buy and ask to plug them into a Zune then an iPod and see which 1 sounds much better to you, and which interface makes you smile much more. Then youll know which is proper for you. 24812
Corgislot Casino https://taxiserviceleidscherijn.nl/lieve-casino-apps-afwisselend-corgislot-nederland-topkeuze-voor-2024/
Hey! Do you use Twitter? I’d like to follow you if that would be ok. I’m undoubtedly enjoying your blog and look forward to new updates.
kra40 at
Thanks for sharing your thoughts. I really appreciate your efforts and I will be waiting for your further post thanks once again.
https://http-kra40.cc
I blog often and I genuinely thank you for your information. This article has truly peaked my interest. I will book mark your blog and keep checking for new details about once per week. I subscribed to your RSS feed as well.
https://http-kra40.cc
Currently it seems like WordPress is the preferred blogging platform available right now. (from what I’ve read) Is that what you are using on your blog?
официальный сайт kra40.at
Hey there! Would you mind if I share your blog with my zynga group? There’s a lot of people that I think would really enjoy your content. Please let me know. Thanks
официальный маркетплейс kra40.cc
Thanks for some other magnificent post. Where else could anyone get that kind of info in such an ideal manner of writing? I have a presentation next week, and I’m on the search for such information.
https://http-kra40.cc
This is my first time go to see at here and i am truly pleassant to read everthing at alone place.
корпус для авто фар
823929 951673Spot ill carry on with this write-up, I truly feel this website requirements a terrific deal far more consideration. Ill oftimes be once far more to see far a lot more, many thanks that information. 238095
300495 156882I really like your writing style, amazing data, thankyou for posting : D. 553155
Corgislot Casino https://lavozdehonduras.com/liefste-nederlandse-online-casinos-corgislot-bergtop-beoordeelde-nl-casinos/
What’s up, I desire to subscribe for this website to obtain most recent updates, therefore where can i do it please help.
батареи отопления
This piece of writing is actually a nice one
it helps new web viewers, who are wishing for blogging.
Visit my site – pink salt trick recipe
https://topblognews.ru/
498007 630479Enjoyed looking at this, extremely great stuff, thanks . 142789
956604 569765We clean up on completion. This may sound obvious but not several a plumber in Sydney does. We wear uniforms and always treat your home or workplace with respect. 146945
горшок с автополивом горшок с автополивом .
753257 550775I dont believe Ive scan anything like this before. So great to find somebody with some original thoughts on this subject. thank for starting this up. This website is something that is necessary on the internet, someone with just a little originality. Good job for bringing something new to the internet! 167133
водка казино
It’s amazing in favor of me to have a website, which is valuable in support of my experience. thanks admin
Bi-LED
the best value|Find out the effective way of treating ED. Visit nolvadex side effects bodybuilding at TamoxiNolva.com – TamoxiNolva from sites that don’t post info about their company.
Heya are using WordPress for your site platform? I’m new to the blog world but I’m trying to get started and set up my own. Do you require any html coding knowledge to make your own blog? Any help would be really appreciated!
Bi-LED
Can I just say what a relief to find a person that actually knows what they are discussing on the net. You actually understand how to bring a problem to light and make it important. More people really need to look at this and understand this side of your story. I can’t believe you aren’t more popular since you surely possess the gift.
Bi-LED
Five Stars Market Binary Options: Pathway to Smarter Trading
Five Stars Market Binary Options give traders a clear and efficient way to participate in global financial markets. With simple tools, transparent conditions, and fast execution, both beginners and experts can explore new opportunities while managing risks effectively. By visiting https://ivr-nurse.jp/ , investors can learn more about Five Stars Market, enhance strategies, and work toward consistent results in binary options trading.
ZenTrader Binary Options: Clear Strategies for Modern Investors
ZenTrader Binary Options provide a simple yet powerful approach to global trading. With fast execution, transparent tools, and flexible strategies, both beginners and professionals can balance risks while seeking growth. By exploring ZenTrader through https://shoku-academia.jp/, traders gain valuable knowledge, sharpen decision-making skills, and build confidence to achieve smarter and more consistent results in today’s financial markets.
Wow, superb blog layout! How long have you ever been running a blog for? you made running a blog look easy. The total glance of your website is fantastic, as well as the content!
https://6csfail.net/en/cs2-roulette/
Предлагаем вашему вниманию интересную справочную статью, в которой собраны ключевые моменты и нюансы по актуальным вопросам. Эта информация будет полезна как для профессионалов, так и для тех, кто только начинает изучать тему. Узнайте ответы на важные вопросы и расширьте свои знания!
Разобраться лучше – https://vyvod-iz-zapoya-1.ru/
Hey very cool website!! Man .. Excellent .. Superb .. I’ll bookmark your blog and take the feeds also? I am satisfied to seek out so many helpful information right here within the submit, we need develop extra strategies in this regard, thank you for sharing. . . . . .
официальный сайт leebet
Good post but I was wondering if you could write a litte more on this topic? I’d be very grateful if you could elaborate a little bit further. Thank you!
регистрация зума казино
https://gidroponik32.ru/