NHibernate / ActiveRecord: how to set a foreign key without getting the whole object?

Let's say I have the following ActiveRecord class:

[ActiveRecord]
public class Account
{
    ...

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

Currently, in order to set the value of the CustomerId field, I have to get the entire Customer object from the database and assign it to my account:

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

It is not very effective. I would prefer to set the value of the CustomerId field directly without rounding the database, for example.

account.CustomerId = 1;

What is the right way to do this?

+3
source share
4 answers

You can implement MK8k solution in ActiveRecord. It will look like this:

using (new SessionScope()) {
    var ghostCustomer = Customer.Find(customerId);

    var account = Account.TryFind(accountId);
    account.Customer = ghostCustomer;
}

Two important points:

SessionScope. Find , SessionScope .

Customer . NHibernate .

0

, Castle ActiveRecord NHibernate ( ISession.Get ISession.Load?), , NHibernate :

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

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

ghostCustomer -, . , .

, , .

+2

, . , , , . , .

+1

Source: https://habr.com/ru/post/1703422/


All Articles