NHibernate / ActiveRecord:如何在不获取整个对象的情况下设置外键?
作者:互联网
假设我有以下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;
正确的方法是什么?
解决方法:
您可以在ActiveRecord中实施MK8k的解决方案.它看起来像这样:
using (new SessionScope()) {
var ghostCustomer = Customer.Find(customerId);
var account = Account.TryFind(accountId);
account.Customer = ghostCustomer;
}
两个要点:
Customer.Find必须在SessionScope中.如果未定义SessionScope,则Find方法将检查并完全加载您的对象.
客户类必须定义为惰性. NHibernate不会将代理用于非惰性类.
标签:activerecord,nhibernate,castle-activerecord,c 来源: https://codeday.me/bug/20191108/2004382.html