NHibernate Pitfalls: Loading Foreign Key Properties

This is part of a series of posts about NHibernate Pitfalls. See the entire collection here.

When saving a new entity that has references to other entities (one to one, many to one), one has two options for setting their values:

  • Load each of these references by calling ISession.Get and passing the foreign key;
  • Load a proxy instead, by calling ISession.Load with the foreign key.

So, what is the difference? Well, ISession.Get goes to the database and tries to retrieve the record with the given key, returning null if no record is found. ISession.Load, on the other hand, just returns a proxy to that record, without going to the database. This turns out to be a better option, because we really don’t need to retrieve the record – and all of its non-lazy properties and collections -, we just need its key.

An example:

   1: //going to the database
   2: OrderDetail od = new OrderDetail();
   3: od.Product = session.Get<Product>(1);    //a product is retrieved from the database
   4: od.Order = session.Get<Order>(2);        //an order is retrieved from the database
   5:  
   6: session.Save(od);
   7:  
   8: //creating in-memory proxies
   9: OrderDetail od = new OrderDetail();
  10: od.Product = session.Load<Product>(1);    //a proxy to a product is created
  11: od.Order = session.Load<Order>(2);        //a proxy to an order is created
  12:  
  13: session.Save(od);

So, if you just need to set a foreign key, use ISession.Load instead of ISession.Get.

                             

No Comments