NHibernate的/ ActiveRecord的:如何设置没有得到整个物体的外键? [英] NHibernate / ActiveRecord: How to set foreign key without getting entire object?
问题描述
比方说,我有以下ActiveRecord类:
Let's say I've got the following ActiveRecord class:
[ActiveRecord]
public class Account
{
...
[BelongsTo("CustomerId")]
public Customer Customer { get; set; }
}
目前,要我必须从数据库中获取整个客户对象,并将其分配给帐户设置在客户字段的值:
Currently, to set the value of the CustomerId field I have to get the entire Customer object from the database and assign it to the Account:
Customer customer = Customer.FindById(1);
account.Customer = customer;
这是效率不高。我宁愿直接设置客户id字段的值,而无需往返数据库,如:
This isn't very efficient. I'd rather set the value of CustomerId field directly without round-tripping the database, e.g.
account.CustomerId = 1;
什么是做了正确的方法是什么?
What's the correct way to do this?
推荐答案
您可以实现MK8k在ActiveRecord的解决方案。它是这样的:
You can implement MK8k's solution in ActiveRecord. It would look like this:
using (new SessionScope()) {
var ghostCustomer = Customer.Find(customerId);
var account = Account.TryFind(accountId);
account.Customer = ghostCustomer;
}
两个要点:
的Customer.Find必须在SessionScope。 Find方法检查,并会完全加载如果SessionScope没有定义你的对象。
The Customer.Find must be in a SessionScope. The Find method checks and will fully load your object if a SessionScope is not defined.
Customer类必须定义为懒惰。 NHibernate的将不使用代理非延迟的类。
The Customer class must be defined as lazy. NHibernate will not use a proxy for a non-lazy class.
这篇关于NHibernate的/ ActiveRecord的:如何设置没有得到整个物体的外键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!