set MySqlParameter = -1 if null

Advertisements

I am trying to use SQL queries, but I meet a problem with nullable objects :

Here is my code where I define all MySql parameters :

MySqlParameter[] listParams = new MySqlParameter[]
{
    new MySqlParameter("id", this.ID),
    new MySqlParameter("idStock", this.idStock),
    new MySqlParameter("certificate", this.certificate),
    new MySqlParameter("idLO", this.launchingOrder.ID),
    new MySqlParameter("idToleOri", this.toleOri.ID),
    new MySqlParameter("idTolesOri", string.Join("+", this.idTolesOri)),
    new MySqlParameter("listInstructions", string.Join("|", this.listInstructions)),
    new MySqlParameter("length", this.length),
    new MySqlParameter("width", this.width),
};

In my case, this.toleOri can be null. I would like to say if toleOri == null, then param.Value = -1.
But when I execute the query, VS gives an error on the line new MySqlParameter("idToleOri", this.toleOri.ID). (because toleOri is null)

How is it possible to solve that? The only way I found is to always initialize tleOri with ID=-1.
I also tried (this.toleOri.ID ?? -1), but then it says that ?? cannot be used for int or doubles. I understand the message, but don’t see how to solve it?

>Solution :

You may try to use this.toleOri == null ? -1 : this.toleOri.ID, then it will assign -1 when this.toleOri is null, and get the ID value of this.toleOri when it is not null.

Leave a ReplyCancel reply