views:

219

answers:

2

I couldn't find an answer to this specific question. I am trying to keep my domain model object-oriented and re-use objects where possible. I am having an issue determining how to provide a mapping to multiple classes from a single row. Let me explain with an example:

I have a single table, call it Customer. A customer has several attributes; but, for brevity, assume it has Id, Name, Address, City, State, ZipCode.

I would like to create a Customer and Address class that look like this:

public class Customer {
    public virtual long Id {get;set;}
    public virtual string Name {get;set;}
    public virtual Address Address {get;set;}
}

public class Address {
    public virtual string Address {get;set;}
    public virtual string City {get;set;}
    public virtual string State {get;set;}
    public virtual string ZipCode {get;set;}
}

What I am having trouble with is determining what the mapping would be for the Address class within the Customer class. There is no Address table and there isn't a "set" of addresses associated with a Customer. I just want a more object-oriented view of the Customer table in code. There are several other tables that have address information in them and it would be nice to have a reusable Address class to deal with them. Addresses are not shared so breaking all addresses into a separate table with foreign keys seems to be overkill and, actually, more painful since I would need foreign keys to multiple tables.

Can someone enlighten me on this type of mapping? Please provide an example if you can.

Thanks for any insights!

-Mike

+7  A: 

You should use a Component in your NHibernate mapping file. For example:

<class name="Customer"
table="Customer">

<id name="Id">
    <generator class="identity"/>
</id>
<property name="Name" />
<component name="Address">
    <property name="Address"/>
    <property name="City"/>
    <property name="State"/>
    <property name="ZipCode"/>
</component>
</class>

More can be read about it in Ayende's blog.

bahadorn
A: 

Very helpful! Worked just as expected. Thanks.

Michael Kurtz