Search code examples
asp.netapidto

itemToDto does not existin current context


Im following this tutorial

On how to create an API with ASP.NET and at some point(Prevent-Overpostinh is the corresponding Headline) i seem to miss some sort of Dependency.

Im getting the Error: "The name 'ItemToDTO' does not exist in the current context"

        public async Task<ActionResult<IEnumerable<EventItemDTO>>> GetEventItems()
        {
            return await _context.EventItems
            .Select(x => ItemToDTO(x))
            .ToListAsync();
        } 

Solution

  • You have to add the function so it can be called

        private static TodoItemDTO ItemToDTO(TodoItem todoItem) =>
            new TodoItemDTO
            {
                Id = todoItem.Id,
                Name = todoItem.Name,
                IsComplete = todoItem.IsComplete
            };   
    

    Edit;

    This is a more concise way of writing:

    private static TodoItemDTO ItemToDTO(TodoItem todoItem)
    {
        return new TodoItemDTO
        {
            Id = todoItem.Id,
            Name = todoItem.Name,
            IsComplete = todoItem.IsComplete
        };
    }
    

    You could also do this without a function call:

    _context.EventItems
        .Select(x => new TodoItemDTO
            {
                Id = x.Id,
                Name = x.Name,
                IsComplete = x.IsComplete
            })