views:

147

answers:

1

How can I have the property of a property set using NHibernate?

Here is an example (just an example!)

public class Person
{
   private FullName _subClassProperty = new FullName();

   public FullName Name
   {
      get { return _subClassProperty; }
      set { return _subClassProperty; }
   }
}

public class FullName
{
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
}

Person is serialized to a database table that looks like this:

table Person { 
    FirstName varchar, 
    LastName varchar 
}

I want to write a mapping file for the Person class so that NHibernate will access the FirstName and LastName properties of the Person's FullName property when serializing/deserializing a Person. I do not want NHibernate to instantiate the FullName class - the Person class should still be in charge of instantiating the FullName class.

I suspect this is possible using an IPropertyAccessor, but I can't find much documentation on how to achieve this. Could someone help an NHibernate newbie out?

+2  A: 

This looks like a classic use case for an NHibernate Component to me. If you're mapping using XML, something like this:

<component name="FullName" class="YourNamespace.FullName, YourAssembly">
    <property name="FirstName" type="String" />
    <property name="LastName" type="String" />
</component>

If you're using Fluent:

Component(p => p.FullName, m =>
{
     m.Map(p => p.FirstName);
     m.Map(p => p.LastName);
});
David M
Ah ok cool, I'll try that. From the little bit of docs I read I thought that components were used for my scenario but backwards - where you have two tables that you want to map to one class.
cbp