0

I'm building an API application and when I call this service method the way it's below, it just works fine:

public IEnumerable<Produtos> GetAll(string term, int page, int pageSize)
        {
            var products = _repository.GetAllProducts().Skip((page - 1) * pageSize).Take(pageSize).ToList();

            return products;
            
        }

It returns a List of objects. Fair enough.

But then, when I implement this logic, it fails to retrieve me any data:

public IEnumerable<Produtos> GetAll(string term, int page, int pageSize)
        {
            var products = _repository.GetAllProducts().Skip((page - 1) * pageSize).Take(pageSize).ToList();

            List<Produtos> produtos = new List<Produtos>();

            products.ForEach(produto =>
                {
                    Console.WriteLine(produto);
                    if (produto.Nome.Contains(term))
                    {
                        Console.WriteLine("if statement");
                        produtos.Add(produto);
                    }
                }
            );
            
            if (!(produtos.Count > 0))
            {
                throw new Exception();
            }

            return produtos;
            
        }

Also, the IDE tells me that there is not an instantiated object:

enter image description here

Strangely, when I debug it, it stops looping over the list when it reaches product.name == "kn"

enter image description here

Here's my db with random values I did insert into.

enter image description here

  • your code and screenshot is not matching, please check. also `produto.Nome` could be `null` – Vivek Nuna Dec 29 '22 at 15:26
  • 2
    Looks like `produto.Nome` or `produto.Categoria` or `produto.Categoria.Nome` doesn't exist. Set a break point at the `if` statement and examine the contents of `produto`. Like @viveknuna said, check your code because it doesn't match the screenshot. – Tim Jarosz Dec 29 '22 at 15:29
  • I just changed the if statement a little bit. But returns the same – Paulo Vitor Dec 29 '22 at 18:49
  • @TimJarosz I did put more info on the post, take a look – Paulo Vitor Dec 29 '22 at 18:59
  • **Don't call `.ToList()` if the return type is `IEnumerable`!** – Joel Coehoorn Dec 29 '22 at 19:02
  • Also: `public IEnumerable GetAll(string term, int page, int pageSize) { return _repository.GetAllProducts().Where(p => p.Nome?.Contains(term) ?? false).Skip((page-1)*pageSize).Take(pageSize); }` – Joel Coehoorn Dec 29 '22 at 19:08
  • @PauloVitor you still didn't do the debugging, we can't do this for you. You have to set a breakpoint at the `if` statement and examine the `produto` variable. Does it contain all the properties you are trying to reference? If not, then you have to back up and look at how the data is being retrieved from the database. – Tim Jarosz Dec 29 '22 at 19:39

0 Answers0