Development With A Dot

Blog on development in general, and specifically on .NET

Sponsors

News

My Friends

My Links

Permanent Posts

Portuguese Communities

Loading Entities from the First Level Cache

You can use the following code to load all entities of a given type from the first level cache (the entities that were loaded from the current session):

   1: //load all entities
   2: public static IEnumerable<T> Local<T>(this ISession session)
   3: {
   4:     ISessionImplementor impl = session.GetSessionImplementation();
   5:     IPersistenceContext ctx = impl.PersistenceContext;
   6:  
   7:     return (ctx.EntityEntries.Keys.OfType<T>());
   8: }

Or a single entity by its id:

   1: //load a single entity by its id
   2: public static T GetFromCache<T>(this ISession session, Object id)
   3: {
   4:     ISessionImplementor impl = session.GetSessionImplementation();
   5:     IPersistenceContext ctx = impl.PersistenceContext;
   6:  
   7:     foreach (DictionaryEntry entry in ctx.EntityEntries)
   8:     {
   9:         if (entry.Key is T)
  10:         {
  11:             if (Object.Equals((entry.Value as EntityEntry).Id, id) == true)
  12:             {
  13:                 return ((T) entry.Key);
  14:             }
  15:         }
  16:     }
  17:  
  18:     return (default(T));
  19: }
Bookmark and Share

Comments

No Comments