I'm having trouble, when I register my route it appears an error in the time the system will make the comparison to see if the NumCarroId that is in the DropDownList is the same one that is in the bank so you can make the change. / p>
Error appearing to me:
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.
Line 28: public ActionResult Adiciona(RotaModel viewModel)
Line 29: {
Line 30: var rotas = ckm.Consulta(viewModel.NumCarroId);
Line 31: // Aqui busca todas as rotas deste veículo
My ViewModel Route:
public class RotaModel
{
public int Id { get; set; }
public decimal Combustivel { get; set; }
public DateTime DataSaida { get; set; }
public int AutorId { get; set; }
public int NumCarroId { get; set; }
public int Km { get; set; }
public Rota CriaRota()
{
Rota rota = new Rota()
{
Id = this.Id,
Combustivel = this.Combustivel,
DataSaida = this.DataSaida,
Km = this.Km
};
if (this.AutorId != 0)
{
Usuario autor = new Usuario()
{
Id = this.AutorId
};
rota.Autor = autor;
}
if (this.NumCarroId != 0)
{
Veiculo numcarroid = new Veiculo()
{
NCarro = this.NumCarroId
};
rota.NumCarro = numcarroid;
}
return rota;
}
public RotaModel(Rota r)
{
this.Id = r.Id;
this.DataSaida = r.DataSaida;
this.Combustivel = r.Combustivel;
if (r.Autor != null)
{
this.AutorId = r.Autor.Id;
}
if (r.NumCarro != null)
{
this.NumCarroId = r.NumCarro.Id;
}
}
public RotaModel()
{
/*
*construtor vazio para ele assumir como default quando for instanciar a classe
*/
}
NumCarroId query:
public IList<Rota> Consulta(int NumCarroId)
{
string hql = "SELECT NumCarroId FROM Rota";
IQuery query = session.CreateSQLQuery(hql);
return query.List<Rota>();
}
My 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("Form");
}
else
{
ViewBag.Usuarios = usuarioDAO.Lista();
ViewBag.Veiculo = veiculoDAO.Lista();
return View("Form", viewModel);
}
}