I am trying to return JSON data from an API. The API endpoint is "/api/getUserSchedule(int id)". It should return back JSON data where it has been filtered according to the staffId value, which is a foreign key to the taskSchedule table.
I can return all the data, as shown here using a different API endpoint
However, I need it to return data based on staffID. I have created an interface which is implemented by a repository.
interface code
public interface ITaskScheduleRepository
{
Task<TaskSchedule> GetUserSchedule(int id);
}
Repository code
public async Task<TaskSchedule> GetUserSchedule(int id)
{
var userTaskSchedule = await _context.TaskSchedules
.Where(s => s.staffId == id)
.ToListAsync();
return userTaskSchedule; // error is here
}
controller code
[HttpGet("{id}")]
public async Task<IActionResult> GetUserTaskSchedule(int id)
{
var taskUserSchedule = await _repo.GetUserSchedule(id);
if(taskUserSchedule != null)
return Ok(taskUserSchedule);
return BadRequest("There are no tasks for this user");
}
error message
Cannot implicitly convert type 'System.Collections.Generic.List' to 'Schedular.API.Models.TaskSchedule' [Schedular.API]csharp(CS0029)
You are trying to return a List<TaskSchedule> (note your .ToListAsync()) call in your repository method) but your interface is defined to return a single TaskSchedule. Update your interface and repository methods to return a List<TaskSchedule>
Task<IList<TaskSchedule>> GetUserSchedule(int id);
and
public async Task<IList<TaskSchedule>> GetUserSchedule(int id)
However, if a staff can only have one schedule, change your repository query to return a single item instead of a list of items.
var userTaskSchedule = await _context.TaskSchedules
.Where(s => s.staffId == id)
.FirstOrDefaultAsync();
return userTaskSchedule; /
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With