Error Object Reference not set to an instance of an Object in c#

Asked

Viewed 608 times

0

I’m in trouble, when I register my route it appears an error at the time the system will make the comparison to see if the Numcarroid that is in Dropdownlist is the same that is in the bank to can make the change.

Error that appears 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 Route Viewmodel:

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
     */
    }

Query of the Numcarroid:

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

    }

2 answers

1

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

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

If you are using c# smaller than version 6:

string hql = string.Format("SELECT * FROM Rota WHERE NumCarroId = {0}", NumCarroId);
  • I did what was described, but you still make the same mistake

  • you are using Nhibernate?

  • Where is the error popping? On which line?

  • use nhibernate,yes error is happening in my controller on line 30

  • I was able to solve the problem that was happening

  • So it’s in the Query method. Put a breakpoint and tell me where this Query method is giving the error

  • ckm was null? Post the solution, please.

  • I did this, the problem that my controller was not importing the class, I probably delete the class import when I went for some tests

Show 3 more comments

0

The import had been deleted when I went to do some tests in my controller, I put another error in the class that makes the query, but I was just making the query to get 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>();
    }

Browser other questions tagged

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