protected internal static object FindByPrimaryKey(Type targetType, object id, bool throwOnNotFound)
{
EnsureInitialized(targetType);
bool hasScope = holder.ThreadScopeInfo.HasInitializedScope;
ISession session = holder.CreateSession(targetType);
try
{
object loaded;
// Load() and Get() has different semantics with regard to the way they
// handle null values, Get() _must_ check that the value exists, Load() is allowed
// to return an uninitialized proxy that will throw when you access it later.
// in order to play well with proxies, we need to use this approach.
if (throwOnNotFound)
{
loaded = session.Load(targetType, id);
}
else
{
loaded = session.Get(targetType, id);
}
//If we are not in a scope, we want to initialize the entity eagerly, since other wise the
//user will get an exception when it access the entity's property, and it will try to lazy load itself and find that
//it has no session.
//If we are in a scope, it is the user responsability to keep the scope alive if he wants to use
if (!hasScope)
{
NHibernateUtil.Initialize(loaded);
}
return loaded;
}
catch (ObjectNotFoundException ex)
{
holder.FailSession(session);
String message = String.Format("Could not find {0} with id {1}", targetType.Name, id);
throw new NotFoundException(message, ex);
}
catch (ValidationException)
{
holder.FailSession(session);
throw;
}
catch (Exception ex)
{
holder.FailSession(session);
throw new ActiveRecordException("Could not perform FindByPrimaryKey for " + targetType.Name + ". Id: " + id, ex);
}
finally
{
holder.ReleaseSession(session);
}
}