views:

455

answers:

1

New to NHibernate and learning it as we are modifying an existing solution to use this ORM. Ideally, the storage structure and object classes need to stay the same, so Ive come across one or two mapping problems.

One class 'Money' has a value and currency. The value is a double and the currency is a foreign key to a list table of currencies.

Money can appear as a type on many objects/tables, so Ive created a CompositeUserType to map it along with a standard mapping to currency. This works fine, but for the life of me I cannot get the currency relationship to lazy load from NHibernate. We use fluent, but am happy for any pointers in hbm.

+2  A: 

Looks like I need to use components, can't see how to add references from those or CompositeUserTypes, though :/

https://forum.hibernate.org/viewtopic.php?f=1&t=947719&start=0

http://blogs.hibernatingrhinos.com/nhibernate/archive/2008/08/13/a-fluent-interface-to-nhibernate---part-2---value.aspx

http://wiki.fluentnhibernate.org/show/StandardMappingComponents

UPDATE

I have got round this issue by using a CompositeUserType and setting up the proxy endpoint on the entity diring the NullSafeGet() method:

public virtual object NullSafeGet(IDataReader dr, string[] names, ISessionImplementor session, object owner)
{
 if (dr == null)
 {
  return null;
 }

 Money value = new Money()
 {
  Value = (double)NHibernateUtil.Double.NullSafeGet(dr, names[0], session, owner)
 };

 string entityName = session.BestGuessEntityName(value.Currency);
 value.Currency = (CurrencyDetails)session.InternalLoad(entityName, (object)DEFAULT_CURRENCY_ID, false, false);

 return value;
}

Not sure if this is the recommended way of doing it, but it works :)

theGecko
Just wanted to mention - don't add 2 answers. It's enough with one - edit it if found anything new. :)
Arnis L.
How strange that not a day later from your posting, I'm trying to solve the *exact same* problem: a Money type that has an Amount and wants that reference to a Currency entity. I don't think it's an unusual design. Went down the same path you did (CompositeUserType) and got stumped at how to implement NullSafeGet(). Your solution works! (Though I ended up hardcoding the entityName -- just the FQTN like "MyNamespace.Currency".) Not sure if it's the best way either, but hey, it's working. Thanks for taking the time to update your post with an answer!
Nicholas Piasecki
How odd, glad to help :)
theGecko