Development With A Dot

Blog on development in general, and specifically on .NET

Sponsors

News

My Friends

My Links

Permanent Posts

Portuguese Communities

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

Comments

serguzest said:

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.

# June 4, 2011 8:24 PM

Ricardo Peres said:

@serguzest:

Same thing in NH!

# June 5, 2011 3:39 AM

i.yusupov said:

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

Thanks.

# February 18, 2013 9:51 AM

Ricardo Peres said:

i.yusupov:

Try this:

public static IEnumerable<T> Local<T>(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);

}

}

}

}

# February 18, 2013 10:32 AM

i.yusupov said:

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

# February 18, 2013 11:23 AM

Ricardo Peres said:

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.

# February 18, 2013 11:53 AM