3

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?

Chaddeus
  • 13,134
  • 29
  • 104
  • 162

4 Answers4

6

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;
}
Waqas Raja
  • 10,802
  • 4
  • 33
  • 38
  • Nope, lemme try it now... brb. – Chaddeus Apr 09 '11 at 13:20
  • +1, but I'd suggest taking both objects into account in your `DBNull` test: `if (obj.MemberId is DBNull || otherObj.MemberId is DBNull)`. Unless, of course, you want to consider two `DBNulls` as being equal, in which case it gets more complicated. – Frédéric Hamidi Apr 09 '11 at 13:24
  • @Chad, (@Frederic Hamidi) is right you also need to consider whether `otherObj is DBNull`, to avoid any exceptions that can occur. – Waqas Raja Apr 09 '11 at 13:27
  • Thank you Frederic for the heads up, in this case only one side is DBNull'able, but I'll keep that in mind. – Chaddeus Apr 09 '11 at 13:29
  • @Chad, you're welcome, and be careful to always compare the objects in the right order then ;) – Frédéric Hamidi Apr 09 '11 at 13:32
1

Just using Convert.IsDBNull should do.

http://msdn.microsoft.com/en-us/library/system.convert.isdbnull(v=VS.90).aspx

tia
  • 9,518
  • 1
  • 30
  • 44
0

try this. this works for me;

string test = DBNull.Value.Equals(obj.Qty) ? string.Empty : obj.Qty.ToString();

Muru Bakthavachalam
  • 1,340
  • 12
  • 8
0
if (!DBNull.Value.Equals(obj.MemberID) && obj.MemberID !=null && obj !=null)

or

if (!DBNull.Value.Equals(obj) && obj.MemberID !=null && obj !=null)

Select whatever applies to your case. This will give you a full proof check.

Marshal
  • 6,551
  • 13
  • 55
  • 91