C
C#•3y ago
ross

Dotnet code generator web api question

I've been trying out the API code generator in visual studio/dotnet, and I had a question about some of the CRUD methods it generates:
// POST: api/VehicleController
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost]
public async Task<ActionResult<Vehicle>> PostMagnet(Vehicle vehicle)
{
if (_context.Vehicles == null)
{
return Problem("Entity set 'Context.Vehicles' is null.");
}
_context.Vehicles.Add(vehicle);
await _context.SaveChangesAsync();

return CreatedAtAction("GetVehicle", new { id = vehicle.Id }, vehicle);
}
// POST: api/VehicleController
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost]
public async Task<ActionResult<Vehicle>> PostMagnet(Vehicle vehicle)
{
if (_context.Vehicles == null)
{
return Problem("Entity set 'Context.Vehicles' is null.");
}
_context.Vehicles.Add(vehicle);
await _context.SaveChangesAsync();

return CreatedAtAction("GetVehicle", new { id = vehicle.Id }, vehicle);
}
What's the purpose of checking if _context.Vehicles == null? Like I understand that you obviously won't be able to add and saveChanges if it were null, but I can't think of a circumstance where it would be null and that check would apply? I see that check is done in Get, GetById, Post, and Delete. Just curious!
9 Replies
Saber
Saber•3y ago
It's useless. The generated code is dogshit
Unknown User
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
Angius
Angius•3y ago
Why would you want repositories, when DbContext is a repository? Just use that directly in your services
ross
rossOP•3y ago
There seems to be a great divide in this discord between using dbcontext directly in the controller or using it in a service. Noticed that almost daily 😆
Unknown User
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
ross
rossOP•3y ago
I'm on the side of calling my service class from my api controller, but as I mentioned. Great divide. I got told the other day that calling to my service classes was useless and that I should just do it in the controller. I was under the impression that violated SRP etc, but hey ho Frontend > API > Service (inc business logic, mapping, dbcontext) is how I usually go
Unknown User
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
ross
rossOP•3y ago
Guessing your DAL is literally just methods that use the dbcontext?
Unknown User
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server