Local Entities with NHibernate
- by Ricardo Peres
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>();
SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/2.0.320/scripts/clipboard.swf';
SyntaxHighlighter.brushes.CSharp.aliases = ['c#', 'c-sharp', 'csharp'];
SyntaxHighlighter.all();