Development With A Dot

Blog on development in general, and specifically on .NET

Sponsors

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
Leave a Comment

(required) 

(required) 

(optional)

(required)