Object comes null in query, even if existing

Asked

Viewed 77 times

1

I have this method in my controller

[HttpDelete]
        public HttpResponseMessage DeletaCidade(int id)
        {
            Cidade cidade = banco.Cidades.Find(id);

            if (cidade == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            banco.Cidades.Remove(cidade);

            try
            {
                banco.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }

            return Request.CreateResponse(HttpStatusCode.OK, cidade);
        }

what passes is when I pass a valid id, I get in the controller, but the city object continues Null. How do I resolve this?

EDIT1

My Model

public class Cidade
    {
        [Key]
        public int id { get; set; }
        [Required]         
        public String nome { get; set; }
    }
  • Cidade cidade = banco.Cidades.Find(id); returns something ?

  • @Leonardobonetti, no. city comes NULL, but ID=33, for example has the city of "Warsaw", for example.

  • the problem this in the query then, would have to edit and put the class banco of banco.Cidades.Find(id);

  • Why are you doing this to me? Don’t want me in the community anymore? The question is valid and not broad, it allows only one answer. Just downvote

  • I also do not know what is happening, I am negative for nothing... relax

  • The first thing you have to make sure is that the Cities collection has some content. Have you checked?

  • @Williamjohnadamtrindade, no break on that line: Cidade cidade = banco.Cidades.Find(id); city is null, has nothing, just null. I understand what you mean

  • If banco.Cidadesit is certain that the find method will not find anything.

  • Got it. I don’t know what to do in this case, because before I did some methods outside the Controller and in this case it was working. I changed it to leave it on the controller and then it didn’t work anymore

  • 1

    His question starts from a false premise :"even existing". Actually your question cannot be answered because the error is not in the presented code. When you say "The question is valid and not broad, it allows only one answer". It’s inaccurate. By comparison, it’s like you ask, "Why doesn’t my computer turn on?" but forgot to check if there was electricity in the building.Got it?

  • @pnet, before launching a question here, debug your code, method by method and line by line

Show 6 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.