将属性映射到 NHibernate 中另一个表的字段

发布于 2024-08-26 07:34:27 字数 243 浏览 3 评论 0原文

考虑以下类:

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

它映射到 Orders 表。是否可以通过外键关系将属性 CustomerName 映射到 Customers 表?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦情居士 2024-09-02 07:34:27

是的,您可以使用 加入 映射为此的元素。另一种选择是映射视图而不是表。但如果可能的话,您应该采用面向对象的方法并映射订单和客户之间的多对多关系。

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.

破晓 2024-09-02 07:34:27

我强烈建议您不要为此使用 。尽管它可以实现您的要求,但它会产生其他问题。

相反,订单应该与客户有关系。然后,您可以根据需要投影名称,尽管使用 order.Customer.Name 更容易。

因此,归结为:

1) 将 Customer 属性添加到 Order

public virtual Customer Customer { get; set; }

2) 映射该属性(在示例中,CustomerId 是 FK 列的名称)

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

3)如果您特别想要拥有 CustomerName 属性,请从 Customer 投影它:

public virtual string CustomerName { get { return Customer.Name; } }

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; } }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文