0

考虑这两个类之间的关系

public class Order
{
  public int OrderId {get;set;}
  public int CustomerId {get;set;}  // Should this be here?
  public Customer Customer{get;set}
}

public class Customer
{
  public int CustomerId {get;set;}
  public string Name {get;set;}
}

我知道我不需要Order上的CustomerId属性,并且我同意这不是最漂亮的 OO 做事方式。只有 Customer 属性,我可以轻松地请求Order.Customer.CustomerId来获取客户的 ID。

但在这种情况下,NHibernate 将触发对数据库的请求以加载该客户,并且有一些(实际上很多)情况我只需要OrderCustomerId。在这种情况下,Order类中的CustomerId将很有用,并且需要更少的访问数据库。(如果我对此有误,请纠正我)。

问题 1:有没有办法告诉 NHibernate 我希望这两个属性总是更新?

属性CustomerId将始终具有客户的 Id,并且只有在我愿意时才会由惰性加载属性Customer(假设获取客户的姓名)。Microsoft Entity Framework 允许这样做。

问题2:如果不可能,我应该担心这个吗?

更新

按照答案说明,我做了一个测试,试图检查为什么(在我的情况下)NHibernate 没有按预期工作,并发现了一些有趣的东西:如果我不使用 Accessor,NHibernate 默认不会在 Order.Customer.CustomerId 访问数据库。映射CustomerId 属性的字段。

使用默认访问器,它可以按预期工作。知道为什么吗?

4

2 回答 2

4

NHibernate 的默认行为是仅在访问 Id 时不加载对象。另一个问题已经回答了这个问题,我在下面引用了这个问题。

如果您A从数据库中检索然后访问A.B.Id这将不会命中数据库。如果您访问除 Id 字段之外的任何其他属性,它将导致 NHibernate 从数据库中检索 B。

因此,总而言之,调用Order.Customer.CustomerId不会触发 NHibernate 来查询数据库以获取客户表中的行,CustomerId因此最好从您的 Order 类中删除 CustomerID。

于 2013-03-19T21:13:46.693 回答
1

Only one property can be writable. I suggest mapping of both like this (we are using this approach):

Class

public int CustomerId {get;set;}  // Should this be here?
public Customer Customer{get;set} // Answer: yes

Mapping

<many-to-one name="Customer" column="CustomerId"  />
<property  name="CustomerId" column="CustomerId" insert="false" update="false" />

Now you can manipulate with both properties in Read operations the same way (e.g. filtering). The bidning of the detached Order must set the Customer, while CustomerId is read only.

So for write operations, you can (and you should) use only one property.

The benefit is, that if you need to filter only by Customer ID, you do not have to manipulate the Customer (object, table) at all.

于 2013-03-20T04:39:03.150 回答