NHibernate / ActiveRecord:如何在不获取整个对象的情况下设置外键?

2024-04-22

假设我有以下 ActiveRecord 类:

[ActiveRecord]
public class Account
{
    ...

    [BelongsTo("CustomerId")]
    public Customer Customer { get; set; }
}

目前,要设置 CustomerId 字段的值,我必须从数据库获取整个 Customer 对象并将其分配给 Account:

Customer customer = Customer.FindById(1);
account.Customer = customer;

这不是很有效。我宁愿直接设置 CustomerId 字段的值,而不需要往返数据库,例如

account.CustomerId = 1;

这样做的正确方法是什么?


我不知道Castle ActiveRecord如何使用NHibernate从数据库加载对象(使用ISession.Get or ISession.Load?),但我知道 NHibernate 可以完成以下操作:

var ghostCustomer = session.Load<Customer>(customerId);

var account = session.Get<Account>(accountId);
account.Customer = ghostCustomer;

Here, ghostCustomer将是一个统一的代理对象,其字段将在第一次访问时延迟加载。但由于我们仅使用它来分配帐户上的客户关系,因此它永远不会实际加载。

因此,此示例中唯一的数据库访问将在加载帐户时以及之后刷新会话并且必须更新帐户时发生。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

NHibernate / ActiveRecord:如何在不获取整个对象的情况下设置外键? 的相关文章

随机推荐