Posts Tagged ‘nullable’

Dear community,

It’s me once more with a small but handy hint that can make your coding and maintaining a bit easier.

When mapping columns to integral types, it certainly is possible that a field’s value is NULL, right? Now, let’s assume a hypothetical table ORDER that contains a field QUANTITY. Assume also that we have an existing mapping that looks like the one in snippet 1:

   1: <property name="Quantity" column="QUANTITY" type="System.Int32"/>

Snippet 1: Excerpt of a Order table HBM file

Assume also the class we’re mapping to, Order:

   1: public class Order

   2: {

   3:     Int32 Quantity;

   4: ...

Snippet 2: Excerpt of the Order class

Now, what happens to this property once we’re actually mapping values from the DB to it?

If the value is NULL, then the property will assume its default value, which in this case i 0.

So what’s wrong with that?

Simply put, this is correct, but not very effective. Imagine a scenario where we have both 0 and NULL values stored in the QUANTITY column. Once the values are mapped, they could not be distinguished from each other anymore, since they would both map to 0 in our property Order.Quantity.

Hence, we need to come up with a more elegant solution:

We simply use Nullable Types

All you have to do is to change the property Quantity into a Nullable Type, as shown in Snippet 3:

   1: public class Order

   2: {

   3:     Int32? Quantity;

   4: ...

Snippet 3: Excerpt of the changed Order class. Note that the Int32 has been turned into a Int32? Nullable Type.

What else do we have to change? Nothing. NHibernate automatically determines that the property is a nullable type and assigns Null to the property in case of a NULL value arriving from DB.

For the above mentioned scenario, now a 0 would be mapped to a 0 (in the class), and an NULL value from DB would be mapped to an actual Null value (in the class).

That’s it! Enjoy mapping with NHibernate!

Till next time & best regards,


Read Full Post »