Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate Evict By Type instead of by instance

I'm migrating an application like this:

Vehicle v = null;
using (ISession session = MyNHibernateSession())
{
    v = Vehicle.FindById(1);
}

using (ISession session = MyNHibernateSession())
{
    // somwwhere into these4 lines Vehicle comes Finded
    DoSomething();
    DoSomething2();
    DoSomething3();
    DoSomething4();
    DoSomething5();
    DoSomething6();

    // if i do this i get an error "another object with the same id etc etc etc
    session.Update(v);
}

I wan't to do something like this:

    session.EvictAllByType(typeof(Vehicle));

is it possible? how?, thanks

like image 850
manuellt Avatar asked Mar 05 '12 16:03

manuellt


1 Answers

This question may be old, but I ended up here while searching for how to do it. So this is how I ended up doing it:

    public static void EvictAll<T>(this ISession session, Predicate<T> predicate = null)
    {
        if (predicate == null)
            predicate = x => true;
        foreach (var entity in session.CachedEntities<T>().Where(predicate.Invoke).ToArray())
            session.Evict(entity);
    }

    public static IEnumerable<T> CachedEntities<T>(this ISession session)
    {
        var sessionImplementation = session.GetSessionImplementation();
        var entities = sessionImplementation.PersistenceContext.EntityEntries.Keys.OfType<T>();
        return entities;
    }
like image 59
Jay Otterbein Avatar answered Oct 24 '22 19:10

Jay Otterbein