Subtract the current value from the previous one

Asked

Viewed 69 times

1

I’m trying to make a supply system, I need it to take the last km registered in the bank of a specific vehicle and be subtracted by the new that will be inserted I’m trying to do so, but it shows no error, but does not subtract. My Controller:

var teste_01 = ckm.ConsultaVeiculo(viewModel.NumCarroId);
var teste_02 = teste_01.OrderBy(a => a.Km).FirstOrDefault();
viewModel.Km = viewModel.Km - teste_02.Km;

And this is my query:

public IList<Veiculo> ConsultaVeiculo(int Ncarro)
    {
        string hql = "SELECT v FROM Veiculo v";
        IQuery query = session.CreateQuery(hql);
        return query.List<Veiculo>();
    }
  • 1

    A first repair is not filtering the Vehicle in the query, if you do not use WHERE in your SQL all supplies will be returned, and what you will get is always the last and not the last of the current Vehicle.

  • @Antóniocampos Normally Where I apply to the controller, not SQL, but I will implement it in the controller and see how it works, if you can put the answer to what Where should look like

  • 1

    string hql = "SELECT v FROM Vehicle v WHERE idCarro=Ncarro"; Replace idCarro with the field name in the database. As for filtering in Controller in my opinion it will not be very advisable because it will always be loading all the records in the table... over time and as the number of records grows your program will lose performance.

  • I understand, I will begin to implement by sql, the problem is that sometimes it interferes in the functioning of the system and I have to implement by the controller to can work.

  • Depending on BD (Oracle, Sql Server, Postgresql etc) can be done also via "Analytic functions"

1 answer

1


First step is to adjust your query:

public IList<Veiculo> ConsultaVeiculo(int Ncarro)
{
    string hql = "SELECT v FROM Veiculo v";
    IQuery query = session.CreateQuery(hql);
    query.setParameter("id", Ncarro); // verificar se o identificador é "id"
    return query.List<Veiculo>();
}

This way you will pick up the vehicle you want, then in your controller:

var carro = ckm.ConsultaVeiculo(viewModel.NumCarroId).FirstOrDefault(); 
viewModel.Km = viewModel.Km - carro.Km;
  • I don’t really understand what that part of the query.setParameter will do and what parametr is pulling

  • query Parameter serves to get the car, the final query would look something like this:select * from vehicle Where id = [parameter value] with this you know which is the car and can take the KM of it and subtract. Without the query you will get all the cars and will consider the first one.

  • He would then take my field where he is selecting the car by id and would compare?

Browser other questions tagged

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