Difference between Get<T> and Load<T>
What's the difference between Get<T>(object id)
and Load<T>(object id)
? The documentation pretty much reads the same. Also, if it matters, in what cases should I use one over the othe开发者_JS百科r?
The reference provided by Brian explains it quite clearly. However, the main difference is that Load
doesn't hit the database to check and load the entity you require, since it assumes you know the entity exists. The object returned by Load
is some kind of proxy that lazily fetches the real data when required or throws an exception if the entity is not found.
Recap:
Load
should be used when you know for sure that an entity with a certain ID exists. The call does not result in a database hit (and thus can be optimized away by NHibernate in certain cases). Beware of the exception that may be raised when the object is accessed if the entity instance doesn't exist in the DB.Get
hits the database or session cache to retrieve the entity data. If the entity exists it is returned, otherwisenull
will be returned. This is the safest way to determine whether an entity with a certain ID exists or not. If you're not sure what to use, useGet
.
http://ayende.com/Blog/archive/2009/04/30/nhibernate-ndash-the-difference-between-get-load-and-querying-by.aspx
Get will return null if the object requested doesn't exist. Load will throw an exception if the object requested doesn't exist. Otherwise, they function exactly the same as far as I can tell.
Load is the optimized way in some cases. Let's think of a Customer, Order relationship and assume that we have an Orders table with CustomerId as the foreign key.
var order = new Order {OrderDate = Datetime.Now };
order.Customer = session.Get<Customer>(customerId);
session.Save(order);
Although we only need the customerId to persist the order object, above code block will first select the customer with that customerId from Customers table then hit the database again to insert the order for that customer.
But if we used :
order.Customer = session.Load<Customer>(customerId);
only the insert statement with that customerId will be executed. Load is the appropriate way in this case.
Get will return Null if the object doesn't exist whereas Load will not return Null - it either returns an object or throws an exception.
Suppose we have Customer
and Order
tables. Order
has a foreign key to Customer
.
You want to create an order for the customer. In this scenario, you are certain that the customer exists on the database, and you don't need actually loading the customer from the database.
Use load()
to create a proxy class of customer for the order to use, then set the foreign key and save, as follows:
Customer customer = session.load<Customer>(id);
Order order = new Order
{
Name = textBoxName.Text,
Type = TextBoxType.Text,
Price= Convert.ToDecimal(textBoxPrice.Text),
Customer = customer
};
精彩评论