Trust me, if the war stories were like this NHib would be a *lot* more widely adopted
Trust me. I've been there, I've felt that pain, I've even
debugged the NHibernate source to figure out what the heck was going
on. Please, I beg of you, tell my tale to those who ask, tell it
truly...and let me be judged accordingly! And let me tell you, this
Hamlet quotation is appropriate because
going through this problem will
make you feel as if your mom just slept with your uncle. Do I take
NHibernate difficulties too seriously?
Maybe.
Anyway, some of you NHib rookies out there might think that if you have
an enumeration, it's easy enough to just map it to an int for DB
storage, like the following:
namespace J
{
enum JusticeCharacteristics
{
Sexy,
Sultry,
Seductive,
*Sassy* // This is fake code homeboy! I can use whatever characters I LIKE!
}
}
and then in the mapping file put the following for a class using the JusticeCharacteristics in a property called "Characteristics":
<property name="Characteristics"
column="JusticeAppeal"
type="Int32" />
Bold in this case stands for
THIS WAY LIES MADNESS.
You see, when you do something like this NHib tries to map back and forth between two different types -
the moment you retrieve the object from the database it is marked as "dirty" and thus you will get an
automatic update call every time you close the NHibernate session.
Trust me, nothing is more confusing than profiling your application and
noticing that you've got random update calls firing every web request!
Certainly a very confusing and time-intensive operation, made quadruply
so when a himbo like myself is trying to figure out what destruction
our team has wrought!
The solution to this problem is actually pretty simple -
just use the enumeration type as the mapped type:
<property name="Characteristics" column="JusticeAppeal" type="
J.JusticeCharacteristics" />
Italic in this case stands for
YOU ARE NOW AN NHIBERNATE NINJA.
Given the skew of the audience that reads this blog, I fully expect:
-
99.999999999999999% of you read this post and thought, "Thanks for sharing something completely obvious" (trust me, it won't be the first time)
-
0.0000000000000001% freaked out and raced to their production application and now have me to thank for saving their system performance
-
one of you doesn't even know what NHibernate is, but that's okay Dad!
I'll explain it to the entire family over dinner this Christmas!
[Update: For the curious, Ben Hart has an explanation of the casting issues that cause this over on his blog.]