NHibernate mapping: UserTypes with many-to-one

2019-05-24 09:09发布

问题:

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.

回答1:

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

https://web.archive.org/web/20090227235136/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 :)