Search code examples
c#nhibernatefluent-nhibernate

How do I map an ICompositeUserType


I am porting a simple working demo from nhibernate to fluent. My existing nhibernate mapping is this:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="MoneyHibernate"
                   namespace="MoneyHibernate">

  <class name="Invoice" table="Invoices">
    <id name="Id">
      <generator class="guid"/>
    </id>
    <property name="Number"/>
    <property name="Customer"/>
    <property name="TotalValue" type="MoneyHibernate.MoneyCompositeUserType,MoneyHibernate">
      <column name="TotalValue_Amount" not-null="true" />
      <column name="TotalValue_Currency" length="3" not-null="true" />
    </property>

  </class>

</hibernate-mapping>

I have tried to create equlivilant ClassMap:

internal class InvoiceMap : ClassMap<Invoice>
{
    public InvoiceMap()
    {
        Id(x => x.Id);
        Map(x => x.Customer);
        Map(x => x.Number);
        Map(x => x.TotalValue)
            .CustomType(typeof (MoneyCompositeUserType))
            .Column("TotalValue_Amount")
            .Column("TotalValue_Currency");
    }
}

But I get the error:

---> NHibernate.MappingException: property mapping has wrong number of columns: MoneyHibernate.Invoice.TotalValue type: MoneyHibernate.MoneyCompositeUserType

So I presume that declaring column twice is not the correct way to do this?


Solution

  • You are doing this the right way, however, you need to add Columns.Clear() to your mapping prior to the manual declaration of the columns like this:

    Map(x => x.TotalValue)
            .CustomType(typeof (MoneyCompositeUserType))
            .Columns.Clear()
            .Columns.Add("TotalValue_Amount", "TotalValue_Amount");
    

    Otherwise nHibernate will append the new column names in addition to the column collection for your composite user type mapping (hence the wrong number of columns exception).