views:

174

answers:

2

consider the following class:

class Order {
    int OrderId {get; set;}
    int CustomerId {get; set;}
    string CustomerName {get; set;}
    //other fields go here
}

which is mapped to Orders table. Is it possible to map the property CustomerName to the Customers table through the foreign key relation?

A: 

Yes, you can use the join mapping element for this. Another option is to map a view instead of a table. But if possible you should take the object-oriented approach and map the many-to-many relationship between Order and Customer.

Jamie Ide
Can you please explain more about the join mapping element? The foreign key is within the Order class/table, not in the other table as in the example page you provided.
Khalil Dahab
A: 

I strongly suggest you don't use <join/> for this. Although it would accomplish what you requested, it creates other problems.

Instead, Order should have a relationship with Customer. You can then project the name if you want, although it's easier to just use order.Customer.Name.

So, it boils down to this:

1) Add Customer property to Order

public virtual Customer Customer { get; set; }

2) Map the property (in the example, CustomerId is the name of the FK column)

<many-to-one name="Customer" column="CustomerId"/>

3) If you specifically want to have a CustomerName property, project it from Customer:

public virtual string CustomerName { get { return Customer.Name; } }
Diego Mijelshon
This is what I have now, howvere it is not efficient; it has to read the whole Customer record in order to display the name.
Khalil Dahab
If you enable caching of Customer instances, it will be even more efficient than join.
Diego Mijelshon
Does NHibernate support caching? or I have to implement it myself?
Khalil Dahab
It does. Read the docs: http://nhforge.org/doc/nh/en/index.html#performance-cache
Diego Mijelshon
I cannot figure it out how to use join for this. According to documentation on Join (http://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html#mapping-declaration-join), the foreign key should be in the table you are referencing, however in my case the foreign key is in the same table.
Khalil Dahab