Mapping a property to a field from another table in NHibernate
-
21-09-2019 - |
Question
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?
Solution
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.
OTHER TIPS
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; } }