Local Entities with NHibernate

You may know that Entity Framework Code First has a nice property called Local which lets you iterate through all the entities loaded by the current context (first level cache). This comes handy at times, so I decided to check if it would be difficult to have it on NHibernate. It turned out it is not, so here it is! Another nice addition to an NHibernate toolbox!


	public static class SessionExtensions
	{
		public static IEnumerable<T> Local<T>(this ISession session)
		{
			ISessionImplementor impl = session.GetSessionImplementation();
			IPersistenceContext pc = impl.PersistenceContext;

			foreach (Object key in pc.EntityEntries.Keys)
			{
				if (key is T)
				{
					yield return ((T) key);
				}
			}
		}
	}
	
	//simple usage
	IEnumerable<Post> localPosts = session.Local<Post>();

Bookmark and Share

                             

6 Comments

  • Fyi, entity frameworks' local collection gets updated while any entity added or removed from the context. I am sure that's possible in nhibernate too but it is hard to know where to start in nhibernate.

  • @serguzest:
    Same thing in NH!

  • As I know, PersistenceContext holds only persisted entities, but how to get added or removed entities?

    Thanks.

  • i.yusupov:

    Try this:

    public static IEnumerable Local(this ISession session, Status status = Status.Loaded)
    {
    ISessionImplementor impl = session.GetSessionImplementation();
    IPersistenceContext pc = impl.PersistenceContext;

    foreach (Object key in pc.EntityEntries.Keys)
    {
    if (key is T)
    {
    EntityEntry entry = pc.EntityEntries[key] as EntityEntry;

    if (entry.Status == status)
    {
    yield return ((T)key);
    }
    }
    }
    }

  • Thanks for your response.

    It seems to work with deleted and edited entities, but when I am adding some new entity to some collection, for example blog.posts.add(new post()), added post doesn't appear in pc.EntityEntries.Keys

  • i.yusupov:
    That's normal, the entities have not been saved yet! One thing is belonging to a collection, another is being managed by NHibernate. If you do a session.Save() on them, they will appear.

Comments have been disabled for this content.