Local Entities with NHibernate

Posted by Ricardo Peres on ASP.net Weblogs See other posts from ASP.net Weblogs or by Ricardo Peres
Published on Tue, 01 Mar 2011 12:47:00 GMT Indexed on 2011/03/01 15:25 UTC
Read the original article Hit count: 336

Filed under:
|
|
|

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

© ASP.net Weblogs or respective owner

Related posts about .NET

Related posts about nhibernate