compare object int or dbnull.value linq

Use

private int? addressID;

public object ID {
    get
    {
        return addressID.HasValue ? addressID.Value as object : DBNull.Value;    
    }
}

instead. This way, if addressID has not been initialized or if it has been deliberately set to null, the ID property will return a DBNull.Value. Otherwise, it will return an int, but you have to cast it yourself from object to int or int?.

Having said that, creation of the null has been called “a billion dollar mistake” by the author, but by now I think it is in the trillions. You should return an int? datatype from the database if you can, in which case, the comparison will always work. I am not sure which ORM do you use, but Dapper and linq2db handle this scenario correctly as far as I know.

Leave a Comment