开发者

Mapping a property to a field from another table in NHibernate

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 t开发者_如何学运维o map the property CustomerName to the Customers table through the foreign key relation?


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.


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; } }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜