C
C#10mo ago
Cyclomatic

Passing DateOnly to controller

What's wrong with this snippet? [HttpGet("ondate")] public async Task<IActionResult> GetAppointmentsByDate([FromQuery]DateOnly date) { var appointments = await _appointmentDatabaseService.GetAppointmentByDate(date); if (appointments != null) { return Ok(appointments); } return NotFound(); } I'm using swagger, and the JSON looks like this: { "year": 2024, "month": 5, "day": 5, "dayOfWeek": 1 } yet I get the default(DateOnly) in my request
9 Replies
Angius
Angius10mo ago
Try just a ISO8601-compatible string yyyy-mm-dd 2024-04-05
Pobiega
Pobiega10mo ago
also, is this .NET 8+?
Cyclomatic
CyclomaticOP10mo ago
It's .net 8. Solved. I had to update my swagger from 6.4 -> 6.5
Pobiega
Pobiega10mo ago
👍
Cyclomatic
CyclomaticOP10mo ago
Is this a bad approach: public async Task<List<AppointmentDto>?> GetDoctorAppointments(int id) { var doctor = await _context.Doctors .FirstOrDefaultAsync(d => d.Id == id); if (doctor == null) { return null; } var appointments = await _context.Appointments .Where(a => a.DoctorId == id) .Select(a => a.ToDto()) .ToListAsync(); _logger.LogInformation("Retrieved all appointments associated with the doctor from the database."); return appointments; } I wanted to return null if the doctor doesn't exist in the database. I know it should work, but just wondering whether this is the right (efficient) way to go about it. A doctor might not have any appointments, but they still exist, so appointments would be an empty list. If they don't exist at all, then null
Angius
Angius10mo ago
Sure, that works
Cyclomatic
CyclomaticOP10mo ago
As opposed to this: /// <summary> /// Retrieves all appointments associated with a specific doctor. /// </summary> /// <param name="id">The ID of the doctor.</param> /// <returns>A list of appointments associated with the doctor, or null if the doctor is not found.</returns> public async Task<List<AppointmentDto>?> GetDoctorAppointments(int id) { var appointments = await _context.Doctors .Where(p => p.Id == id) .Select(p => new { Appointments = p.Appointments.Select(a => a.ToDto()) }) .FirstOrDefaultAsync(); return appointments?.Appointments.ToList(); }
Angius
Angius10mo ago
This would result in one database call fewer
Cyclomatic
CyclomaticOP10mo ago
I'm going with the latter, because you would expect many more appointments than doctors. And it's quick to find an Appointment by primary id ^ and that

Did you find this page helpful?