Search code examples
c#dbnull

How does one reliably check if a nullable property contains no data? DBNull is killing me


I've begun using Massive, by Rob Conery. Awesome little "ORM" and very performant. However, I'm running into issues with System.DBNull comparisons on my nullable fields.

For example, I want to check if a property matches another property (in this example, a long type)

if (obj.MemberId == otherObj.MemberId) return true;

throws exception: Operator '==' cannot be applied to operands of type 'System.DBNull' and 'long'. In this case, obj.MemberId was null (more specifically, DBNull).

Ok, so I check if it's DBNull.Value first right? Like this:

if (obj.MemberId != DBNull.Value)
    return obj.MemberId == otherObj.MemberId;

Cool, that works, at least while obj.MemberId is DBNull, but when it's not (contains a long), another exception: Operator '!=' cannot be applied to operands of type 'long' and 'System.DBNull'.

DBNull is killing me. How does one reliably check if a nullable property contains no data?


Solution

  • Did you tried by using is operator?

    if (obj.MemberId is DBNull)
    {
        // it is null
        return false;
    }
    else
    {
        // has some value
        return obj.MemberId == otherObj.MemberId;
    }