If you do not have the value to compare, save without making the comparison

0

I'm trying to make my application save if it has no value to compare, but it's always going through the comparison, I've already tried to put an if but it still has a problem, this is the class that compares my view to 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 with no 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.

    
asked by anonymous 05.09.2017 / 17:12

1 answer

1

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

You need to validate when there is no larger 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");
}
    
05.09.2017 / 19:55