Home > Software design >  How to filter data by datetime format parameter in ASP.NET WEB API
How to filter data by datetime format parameter in ASP.NET WEB API

Time:04-29

I am trying to get lists of data based on the DateTime parameter. But it's not working as I get the error- AutoMapper.AutoMapperMappingException: Missing type map configuration or unsupported mapping. But when I am trying to retrieve data based on an int ID parameter it's working.Any idea on how to solve the issue?

This is controller code :

    [HttpGet("{pubdate}")]
     public async Task<ActionResult<ToDoListDto>> GetTodListOfDates(DateTime pubdate)
          
        {
            var todo = await _toDoListRepository.GetIncomingToDoAsync(pubdate);
            if (todo == null)
            {
                return NotFound();
            }
            return Ok(_mapper.Map<ToDoListDto>(todo));
        }
    

[HttpGet("{id}")]        
    public async Task<ActionResult<ToDoListDto>> GetTodList(int id)           
    {
        var todo = await _toDoListRepository.GetSpecificTodoAsync(id);
        if (todo == null)
        {
            return NotFound();
        }

        return Ok(_mapper.Map<ToDoListDto>(todo));
    }

My Repository code:

    public async Task<IEnumerable<ToDoList>> GetIncomingToDoAsync(DateTime dateTime)
            {
                return await _context.ToDoLists.Where(c => c.StartDate == dateTime).ToListAsync();
            }

public async Task<ToDoList?> GetSpecificTodoAsync(int taskId)
        {
            return await _context.ToDoLists.Where(c => c.Id == taskId).FirstOrDefaultAsync();

My model for a todo:

public class ToDoListDto
    {
        public int Id { get; set; }
        public string? Title { get; set; }
        public string? Description { get; set; }
        public DateTime StartDate { get; set; }
     }

CodePudding user response:

Your mapping started by the datetime endpoint is trying to map an IEnumerable<ToDoListDto> while your integer endpoint is mapping a single ToDoListDto.

If you want to map each item in the collection individually (which is what the integer ID endpoint is doing), change the mapping in the datetime endpoint to the following:

return Ok(todo.Select(item => _mapper.Map<ToDoListDto>(item));

or, if you want to map the entire collection you have to be explicit and specify the type as IEnumerable<ToDoListDto>:

return Ok(_mapper.Map<IEnumerable<ToDoListDto>>(todo));
  • Related