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.







































safe online pharmacies in canada: SteadyMeds – SteadyMeds
https://steadymedspharmacy.shop/# SteadyMeds
Hello, I wish for to subscribe for this weblog to take most up-to-date updates, therefore where can i do it please help.
best online pharmacy: indian pharmacies safe – online pharmacy no prescription
canadian pharmacy prices: canadian pharmacy world – SteadyMeds
Когда бизнес развивается, manage top отзывы снижает хаос в процессах, документах и рабочем взаимодействии между отделами. Платформа объединяет ключевые процессы в одной системе, чтобы руководитель получал реальную картину по персоналу, задачам, согласованиям и финансам без бесконечных таблиц вручную. Это удобное решение для компаний, которым необходимы контроль, прозрачность работы и развитие бизнеса без лишней рутины и потери времени каждый день.
https://accessbridgepharmacy.com/# AccessBridge
SteadyMeds: best canadian online pharmacy reviews – canadian online pharmacy
legitimate online pharmacy buy medicines online in india overseas online pharmacy
https://formulinepharmacy.shop/# buy drugs online
best mail order pharmacy: mail order pharmacy india – medicine online order
reputable overseas online pharmacies: india pharmacy mail order – pharmacy websites
safe online pharmacies cheapest online pharmacy india п»їinternational drug mart
First off I want to say excellent blog! I had a quick question that I’d like to ask if you do not mind. I was interested to find out how you center yourself and clear your head before writing. I have had difficulty clearing my mind in getting my thoughts out. I do take pleasure in writing but it just seems like the first 10 to 15 minutes are generally lost just trying to figure out how to begin. Any recommendations or tips? Cheers!
Hi 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 require any html coding expertise to make your own blog? Any help would be really appreciated!
https://share.google/UE13BWxIPq5iMjLRC
When I originally commented I appear to have clicked the -Notify me when new comments are added- checkbox and now whenever a comment is added I recieve 4 emails with the same comment. There has to be a means you are able to remove me from that service? Thank you!
AccessBridge Pharmacy online pharmacies AccessBridge
best mail order pharmacy: mail order pharmacy india – no script pharmacy
https://formulinepharmacy.com/# international drug mart
I absolutely love your blog and find many of your post’s to be precisely what I’m looking for. Does one offer guest writers to write content available for you? I wouldn’t mind creating a post or elaborating on a few of the subjects you write regarding here. Again, awesome blog!
https://share.google/j79Ue9aNmEvGBARxY
Thank you for the good writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! However, how can we communicate?
online pharmacy: best online pharmacy india – buy online medicine
My spouse and I absolutely love your blog and find the majority of your post’s to be precisely what I’m looking for. Would you offer guest writers to write content for yourself? I wouldn’t mind publishing a post or elaborating on a few of the subjects you write about here. Again, awesome blog!
https://share.google/z8LyFlSPFxnbaE1Ma
AccessBridge AccessBridge AccessBridge
foreign online pharmacy: FormuLine Pharmacy – online pharmacy no prescription needed
https://formulinepharmacy.shop/# us pharmacy no prescription
I really love your site.. Excellent colors & theme. Did you build this site yourself? Please reply back as I’m planning to create my own blog and would like to find out where you got this from or just what the theme is called. Kudos!
Hmm it appears like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I as well am an aspiring blog writer but I’m still new to the whole thing. Do you have any tips for inexperienced blog writers? I’d certainly appreciate it.
Hey there, You have performed a great job. I’ll definitely digg it and in my opinion suggest to my friends. I am sure they will be benefited from this web site.
pin up pin up az
Hi there are using WordPress for your blog platform? I’m new to the blog world but I’m trying to get started and set up my own. Do you need any html coding expertise to make your own blog? Any help would be greatly appreciated!
References:
Alternative to steroids for bodybuilding
References:
https://lsprintingpress.com/product/file-type-cdr-pdf-coral-draw-version-15-24-coral-version-text-editable-yes-zip-file-include-cdr-pdf-fonts-font-list-colour-profiles-zip-file-size-5-mb-coral-file-height-length-8/
Hi there to all, since I am actually eager of reading this website’s post to be updated daily. It includes good stuff.
https://share.google/OMscMJrBmNzl6Np2I
https://pinupazz.top/ pin up
excellent issues altogether, you just won a new reader. What would you recommend about your publish that you simply made some days in the past? Any sure?
Article writing is also a excitement, if you know after that you can write if not it is complicated to write.
pin up az online pin up az
pin up pin-up oyunu
I visited several websites however the audio feature for audio songs present at this site is in fact excellent.
Tadalafil price: п»їcialis generic – VeritasCare
https://veritascarepharm.shop/# Cialis 20mg price
Kudos! I appreciate it. https://nagagamecloud.blob.core.windows.net/betflix22/betflix/uncategorized/betflik.html
VeritasCare: VeritasCare – VeritasCare
Hi there! This post could not be written any better! Reading through this post reminds me of my old room mate! He always kept talking about this. I will forward this article to him. Pretty sure he will have a good read. Thank you for sharing!
http://corebluehealth.com/# CoreBlue Health
https://civicmeds.com/# best online foreign pharmacies
http://civicmeds.com/# online pharmacy without scripts
order viagra Viagra tablet online Viagra online price
http://civicmeds.com/# onlinecanadianpharmacy
canada pharmacy online legit: good pill pharmacy – canadian online pharmacy reviews