Mapping a property to a field from another table in NHibernate

懵懂的女人 提交于 2019-12-01 12:28:31

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/2485123/mapping-a-property-to-a-field-from-another-table-in-nhibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!