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.