Error Object reference not set to an instance of an object in C # [closed]

0

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);
        }

    }
    
asked by anonymous 04.09.2017 / 17:13

2 answers

1

You return a IList<Rota> in your method, however, the query returns only INT (NumCarroId). Change your query to:

string hql = $"SELECT * FROM Rota WHERE NumCarroId = {NumCarroId}";

If you are using C # less than version 6:

string hql = string.Format("SELECT * FROM Rota WHERE NumCarroId = {0}", NumCarroId);
    
04.09.2017 / 18:35
0

The import had been deleted when I went to do some tests in my controller, but I got another error in the class that makes the query, but I was only to have the query take all the results, the controller analyzes what will be necessary .

Controller:

public class RotaController : Controller
{
    private RotaDAO dao;
    private ControleKm ckm;
    private UsuarioDAO usuarioDAO;
    private VeiculoDAO veiculoDAO;

    public RotaController(RotaDAO dao, UsuarioDAO usuarioDAO, VeiculoDAO veiculoDAO, ControleKm ckm)
    {
        this.veiculoDAO = veiculoDAO;
        this.dao = dao;
        this.ckm = ckm; // Essa linha havia sido apagada, por isso estava com erro
        this.usuarioDAO = usuarioDAO;
    }

Query Class:

public class ControleKm : Controller
{
    private Rota r;
    private ISession session;
    public ControleKm(ISession session, Rota r)
    {
        this.r = r;
        this.session = session;
    }

    public IList<Rota> Consulta(int NumCarroId)
    {
        string hql = "SELECT r FROM Rota r";
        IQuery query = session.CreateQuery(hql);
        return query.List<Rota>();
    }
    
04.09.2017 / 21:55