Search code examples
c#nhibernateactiverecordcastle-activerecord

NHibernate / ActiveRecord: How to set foreign key without getting entire object?


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;

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?


Solution

  • 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;
    }
    

    Two important points:

    The Customer.Find must be in a SessionScope. The Find method checks and will fully load your object if a SessionScope is not defined.

    The Customer class must be defined as lazy. NHibernate will not use a proxy for a non-lazy class.