The null value automatically changes to 0

4

I'm doing a vehicle registration, I need it to register that whenever a vehicle is registered to zero instead of the value null, I tried by default, but it does not record the information.

I'm using SQL Server along with C # in visual studio.

Controller class:

public ActionResult Adiciona(VeiculoModel viewModel)
{
  if (ModelState.IsValid)
  {
    Veiculo Veiculo = viewModel.CriaVeiculo();
    dao.Adiciona(Veiculo);
    //return View();
    return RedirectToAction("Form");
  }
  else
  {
    return View("Index", viewModel);
  }
}

DAO Class:

public void Adiciona(Veiculo post)
{
  ITransaction tx = session.BeginTransaction();
  session.Save(post);
  tx.Commit();
}
    
asked by anonymous 28.08.2017 / 20:00

3 answers

6

Generate a INSERT using COALESCE (or ISNULL ) that generates the final query:

INSERT INTO Veiculo(nome, valor)
VALUES('Gol', COALESCE(NULL, 0));

And, of course, change the column to NOT NULL

Or, make the application still, preferably in the CriaVeiculo method:

veiculo.valor = this.valor ?? 0;
// ou
veiculo.valor = 0;
    
28.08.2017 / 20:09
3

You can also set the value of the KM field to 0, as default in SQL SERVER. To do this, go to the Design of your table, select the KM field and set the Default Value or Binding to 0

    
31.08.2017 / 19:34
1

SQL SERVER:

SELECT ISNULL(CAMPO,'VALOR') FROM TABELA
    
31.08.2017 / 19:22