Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

set MySqlParameter = -1 if null

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading