If it has no value to compare, save without comparing

Asked

Viewed 48 times

0

I’m trying to make my application save if it has no value to compare, however you are always going through the comparison, I tried to put an if but still problem, this is the class that makes the comparison between my view and my database.

Controller:

[HttpPost]
    public ActionResult Adiciona(RotaModel viewModel)
    { 

            var rotas = ckm.Consulta(viewModel.NumCarroId);
            //  Aqui busca todas as rotas deste veículo

            var maiorRota = rotas.OrderByDescending(r => r.Km).FirstOrDefault();
            //  Aqui você tem a última rota cadastrada, considerando a regra geral  


            if (viewModel.Km < maiorRota.Km)
            {
                ModelState.AddModelError("Km_Atual.Invalido",
                "A quilometragem precisa ser maior que a anterior");
            }
        if (ModelState.IsValid)
            {
            Rota rota = viewModel.CriaRota();
            dao.Adiciona(rota);
            //return View();
            return RedirectToAction("Index");
            }
        else
            {
            ViewBag.Usuarios = usuarioDAO.Lista();
            ViewBag.Veiculo = veiculoDAO.Lista();
            return View("Form", viewModel);
            }
    }

When I try to save without any pre-registered value, it appears the following error.

Description: An unhandled Exception occurred During the Execution of the Current web request. Please review the stack trace for more information about the error and Where it originated in the code.

Exception Details: System.Nullreferenceexception: Object Reference not set to an instance of an Object.

1 answer

1


The Enumerable.FirstOrDefault() no argument for default brings the null value when not found a value within your collection. What happens is that if it does not find anything you will be accessing a property (.km) of a null reference, this will cause your NullReferenceException

You need to validate when there is no major route to make the comparison. An example of how to validate:

var maiorRota = rotas.OrderByDescending(r => r.Km).FirstOrDefault();

if (maiorRota != null && viewModel.Km < maiorRota.Km)
{
    ModelState.AddModelError("Km_Atual.Invalido",
            "A quilometragem precisa ser maior que a anterior");
}
  • It worked, but I’m kind of sorry to ask for one more thing, but could you explain to me what this != null would be and how would you interpret it

  • No problem, the reason of the forum is to ask and I am happy to answer. null is a "representation" that my variable does not reference anything. If I try to access something from a variable that references nothing, this exception occurs. Then the interpretation would be: If my mother has something to say.

  • 1

    I was trying to do so so null I put the 0, and I was creating another if/lse to try to do this, but still it was going wrong, so I get much shorter and easier to understand.

Browser other questions tagged

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