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 other?
Difference between Get and Load
nhibernate
Related Topic
- C# – What’s the difference/advantages between ICriteria and ICriterion in nHibernate
- What’s the difference between DetachedCriteria and ICriteria
- The difference between JoinQueryOver and JoinAlias
- Difference between CallSessionContext, ThreadLocalSessionContext and ThreadStaticSessionContext
- Hibernate – Criteria.DISTINCT_ROOT_ENTITY vs Projections.distinct
Best Answer
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 byLoad
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
.